I have created a class called BasePage which inherits System.Web.UI.Page. On this page I’ve declared a property called UserSession which I want to be able to access from any Page/MasterPage.
public class BasePage : System.Web.UI.Page
{
string UserSession { get; set; }
public BasePage()
{
base.PreInit += new EventHandler(BasePage_PreInit);
}
private void BasePage_PreInit(object sender, EventArgs e)
{
UserSession = "12345";
}
}
My Default.aspx.cs page inherits the BasePage class and allows me to access the UserSession property as expected.
public partial class Default : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(UserSession);
}
}
However, even though Default.aspx has MasterPage.Master assigned correctly, when I try and access the UserSession property from MasterPage.Master.cs it can’t find it and won’t build.
So what am I trying to achieve by doing this? I want to expose a UserSession object to every page in my application. Pretty simple you would have thought? Nope.
MasterPageis separate in the heirarchy toPageso you cannot access the property directly from that. However,MasterPagedoes have aPageproperty that returns thePageobject, which you can cast to yourBasePageclass. Then as long asUserSessionis public (or internal, or protected internal, which might make good sense here) it can access that property. Unless you’ve only one master page codebehind, you may want to similarly create a BaseMasterPage and do something like: