Variables from Master Page always empty

2019-08-27 02:38发布

问题:

I have these variables set on my MasterPage

    public string CurrentUser = "";
    public string UserDomain = "";

    protected void Page_Load(object sender, EventArgs e)
    {

        string Name = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
        string[] userDetails = Request.LogonUserIdentity.Name.Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries);
        UserDomain = userDetails[0];
        CurrentUser = userDetails[1];
    }

In a child page I am simply trying to read those values back:

CurrentUser = ((SiteMaster)Page.Master).CurrentUser;
UserDomain = ((SiteMaster)Page.Master).UserDomain;

They are always coming back empty. I can see that they are set correctly on the Master page but they get lost on the way to the content page.

What am I doing wrong?

回答1:

The Master page Load event comes after the Content page Load event. That probably means that the variables get initialized after they are accessed in your content page.

You could opt to set those properties in the Init event of the masterpage, or initialize them on accessing a property.

See Events in ASP.NET Master and Content Pages.