Suppose I have a web project and a bunch of different Web Forms, effectively all different classes inheriting System.Web.UI.Page.
I decided it’d be great to have some fields, methods, and a few things to happen in the Page_Load method of any page I use in my project.
Off the cuff, I thought perhaps to make a class, say MasterPage, that has all the fields and methods I want (with protected level) and have this class inherit System.Web.UI.Page.
Then every page in my project should now inherit from MasterPage instead of System.Web.UI.Page.
While this worked, there were a couple problems with it.
-
I couldn’t really “catch” forms that were still inheriting from
System.Web.UI.Pagevery easily. Is there an easy way? -
Due to the way it was setup, the MasterPage’s PageLoad is virtual and has to be overridden e.g.:
protected override void Page_Load(object sender, EventArgs e) { base.Page_Load(sender, e); // rest of stuff for this page... }Is there any easier way to have the parent’s method always called first without explicitly putting in the base call in every page?
OnInit()in your base class so you don’t have to worry about whichPage_Loadwas called first.Another completely different solution is to use ASP.NET Master Pages. This is usually the best way to share content across all pages in a web application.