tags:

views:

23

answers:

3

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.

+1  A: 

It is simple. Declare your string variable as public.

TheGeekYouNeed
A: 

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.

mhughes
+1  A: 

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;
    }
  }
}
Jon Hanna
Is there any way of exposing an unlimited number of properties without having to declare each of them individually in the BaseMasterPage?
James Law
You could expose the `(Page as BasePage)` itself, and call it through `BasePage.UserSession` etc. though I'd argue against as exposing a bit much.
Jon Hanna