The
auto-generated ASP.NET page class must extend the
Page
class (as shown in the code below), You can optionally create
a base class from which all pages will derive from, When creating a base class,
you'll typically have this base class extend the Page
class. If you are using the code-behind model your
code-behind classes will need to be modified to inherit from the new base class
as opposed to the Page
class. This gives you greater flexibility in controlling your
application and reduce code significantly if done correctly for example if you
where to place a simple check of user roles and check access on any number of
pages by just Inheriting the page from the custom base class you created. Standard ASP.NET page code
public class WebForm1 : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
}
#region Web Form Designer generated code
... code removed for brevity ...
#endregion
}
Base Page class inheriting System.Web.UI.Page
public class MyBaseClass : System.Web.UI.Page
{
protected override void OnLoad(EventArgs e)
{
// ... add custom logic here ...
// Be sure to call the base class's OnLoad method!
base.OnLoad(e);
}
}
Now Page is inheriting from MyBaseClass and not directly from the Page Class
public class WebForm1 : MyBaseClass
{
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
}
}
Now in the above code we see that in the MyBaseClass we are overriding the page load method and can add custom code here, I posted a example of base page implementation in my earlier blog about Multilingual website where we had easily implemented the base page across the website and checked the database for user language preference and updated the page culture accordingly with minimal code.
You can get tips on good usage of Base page from this article http://dotnetslackers.com/articles/aspnet/Four-Helpful-Features-to-Add-to-Your-Base-Page-Class.aspx
In the end I would like to state that with Base page you can handle a complex task or a very simple task within the page execution cycle and not having to re-write the code at several locations.
No comments:
Post a Comment