简体   繁体   中英

Session in master page asp.net

I have master page containing login and logout button.

I want it visible and invisible when session["Userid"] is null.

How can I do that?

I know how to make visible and invisible

  • code is:

     protected override void OnInit(EventArgs e) { base.OnInit(e); //string s = Session["UserId"].ToString(); if (Session["UserId"] != null) { divLogin.Visible = true; divLogout.Visible = false; } else { divLogin.Visible = false; divLogout.Visible = true; } } 

    Please help.

  • You can also achieve this with this code in HTML. Try,

    <div id="divLogin" style="display: <%= Session["UserId"]!=null ? "none" : "block" %>">Your Login content</div>
    <div id="divLogout" style="display: <%= Session["UserId"]==null ? "none" : "block" %>">Your Logout content</div>
    

    You must set runat="server" for the div.

    <div id="divLogin" runat="server"></div>
    

    Code Behind

    divLogin.visible=false;
    

    Use the logic in OnPreRender function as user login & logout always occurs after OnInit is called for the master page. So, during refresh you will get proper values but not the first time.

    From MSDN you can find the below information

    Master pages behave like child controls on a page: the master page Init event occurs before the page Init and Load events, and the master page Load event occurs after the page Init and Load events.

    What I think is (most probably) you are setting the user's login information in the Login page's buttonClick event handler, which gets called after the OnInit of the master page. So when the master page's OnInit gets executed, Session already contains previous state (null during login and user information during logout)

    Even if the login controls and login button are provided on the Master page, it is better to provide this logic in PreRender event.


    Glad to help! Please remember to accept the answer if you found it helpful.

    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