Extend custom System.Web.UI.Page implementer to include custom property than can be accessed by page and master page
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.
MasterPage
is separate in the heirarchy to Page
so you cannot access the property directly from that. However, MasterPage
does have a Page
property that returns the Page
object, which you can cast to your BasePage
class. Then as long as UserSession
is 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:
public BaseMasterPage : MasterPage
{
protected string UserSession
{
get
{
return (Page as BasePage).UserSession;
}
set
{
(Page as BasePage).UserSession = value;
}
}
}
It is simple. Declare your string variable as public.
EDIT: TheGeekYouNeed's answer is correct... I should know better than to try to answer questions this early on a Monday.
I think you'll need to create a base master page class which holds your UserSession property. This would allow you to access the property from the masterpage as well as the pages that inherit from it.
精彩评论