Let’s say in every page we need to get username and email ID, there are 2 ways we can do it. We could use file include (.inc files) or use page cotroller logic
SiteSettings has 2 properties, Name and Email ID. You can have your own logic to fetch information from database – may be use Table data gateway logic
SiteSettings.cs
using System;
using System.Data;
using System.Configuration;
///
/// Summary description for SiteSettings
///
public class SiteSettings
{
public SiteSettings()
{
}
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
private string _emailAddress;
public string EmailAddress
{
get { return _emailAddress; }
set { _emailAddress = value; }
}
#region Load functions
public void FetchData()
{
//implement your logic to fetch data from config file, DB or other datasources
_name = "xyz";
_emailAddress = "xyz@abc.com";
}
#endregion
}
Create a new BasePage class derived from System.Web.UI.Page. Create an event for ‘Init’ . In the event, load SiteSettings values
BasePage.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
///
/// Summary description for BasePage
///
public class BasePage : Page
{
protected SiteSettings siteSettings;
public BasePage()
{
Init += new EventHandler(BasePage_Init);
}
void BasePage_Init(object sender, EventArgs e)
{
siteSettings = new SiteSettings();
siteSettings.FetchData();
}
}
Now that we have the base class let’s implement BasePage
Page1.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Page1 : BasePage
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.Load += new EventHandler(Page_Load);
}
//protected System.Web.UI.WebControls.Label pageNumber;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DisplaySettings();
}
pageNumber.Text = "2";
}
private void DisplaySettings()
{
eMail.Text = siteSettings.EmailAddress;
userName.Text = siteSettings.Name;
}
}
No comments:
Post a Comment