Search code examples
asp.netmaster-pages

How to turn on the visibility of a <a> which is on the master page from code behind file?


Here is the snippet of the code inside my master page.

<section id="login">
    <asp:LoginView runat="server" ViewStateMode="Disabled">
        <AnonymousTemplate>
            <ul>
                <li><a id="loginLink" runat="server" href="~/Login.aspx">Log in</a></li>
                <li><a id="logoutLink" runat="server" href="#" visible="false">Logout</a></li>
            </ul>
        </AnonymousTemplate>
    </asp:LoginView>
</section>

I would like to turn on the visibility of hyperlink with the id of #logoutlink from one of my pages' code behind file. I tried this way but didn't work.

protected void Page_Load(object sender, EventArgs e)
{
    HyperLink x = (HyperLink)Master.FindControl("logoutLink");
    x.Visible = true;
}

Any help would be appreciated.


Solution

  • You will need to add an ID for LoginView:

    asp:LoginView runat="server" ViewStateMode="Disabled" ID="loginView"
    

    And then the below code will work:

    var loginView = Master.FindControl("loginView");
    var ul = loginView.Controls[0];
    var loginLink = ul.FindControl("logoutLink");