简体   繁体   中英

c# Accessing MasterPage elements from Child Page

I've looked at several examples online and none of then seem to work for me.

All I am trying to do is access the contents of a label from the masterpage header.

Here is what i have..

A Label on the Content Page

<asp:Label ID="StaffUserName" runat="Server" />

A Label on the MasterPage called "ThisLoginName"

    <header>
        <div class="content-wrapper">
            <div class="float-left">
                <p class="site-title">
                    <a runat="server" href="~/">Home</a>
                </p>
            </div>
            <div class="float-right">
            <section id="login">
                Welcome! <b><asp:Label ID="ThisLoginName" runat="server" /></b>

            </section>
            <nav>
                <ul id="menu">
                    <li><a runat="server" href="~/">Home</a></li>
                    <li><a runat="server" href="~/Admin">Admin</a></li>

                </ul>
            </nav>
        </div>
    </div>
</header>

I've read a few tutorials online but i can't seem to work this out. I do however have this at the top of my content page

<%@ MasterType VirtualPath="~/Site.Master" %>

If anyone can help i'd appreciate it.

You need to Add Public properties in Master page class:

public string LabelText 
{ 
get { return StaffUserName.Text; } // StaffUserName is the ID of your LABEL
set { StaffUserName.Text = value; } 
} 

Seeing you have added: <%@ MasterType VirtualPath="~/Site.Master" %> , So in your content page access this as:

Master.LabelText = "MyText";

OR

string test= Master.LabelText;

Fixed..

It was down to the fact that my code to pull the username from the windows login was running at Page load in the masterpage.

So i moved it to the

public void master_Page_PreLoad(object sender, EventArgs e)

section and then it worked.

So it must have been working all along but was pulling through an empty field.

Thanks

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