简体   繁体   中英

How do I send a string or value from the Site.Master.cs to my Default.aspx.cs to the value/string in a label/textbox?

Thanks for reading. I want to set the value obtained in Label1 (in Site.Master.cs) to be passed on to Label2 (in Default.aspx.cs). I want to use it as a value to cross reference data in an SQL db later on in the project.

I just can't seem to get my head around this one.

In Site.Master.cs

namespace flexpoolWeb
{
    public partial class SiteMaster : MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var windowsIdentity = HttpContext.Current.User.Identity;

            if (windowsIdentity == null)
                throw new InvalidOperationException("WindowsIdentity is null");

            string nameWithoutDomain = HttpContext.Current.User.Identity.Name.Split('\\').Last();
            //serverside code httpContext haalt ingelogde gebruiker op in de sessie.

            Label1.Text = String.Format(nameWithoutDomain);

            Label2.Text = MyMaster.UserName;

        }
        public string UserName
        {
            get { return Label1.Text; }
            set { Label1.Text = value; }
        }
    }
}

In Default.aspx.cs:

namespace flexpoolWeb
{
    public partial class _Default : System.Web.UI.Page //instead of : Page
    {
        private SiteMaster MyMaster => ((SiteMaster)Master);

    }
}

Thanks in advance.

Edit: added the answer from Skye MacMaster

Your master page is derived from MasterPage. So you need to type cast Master from MasterPage to whatever the name your master is. I'm guessing Site or SiteMaster. Also, I usually create a private property to avoid having a bunch of ugly typecasting.

public partial class Default : System.Web.UI.Page
{
    private SiteMaster MyMaster => ((SiteMaster) Master);

    protected void Page_Load(object sender, EventArgs e)
    {
        Label2.Text = MyMaster.UserName;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM