简体   繁体   中英

Session and Page.IsPostBack

I have a website in ASP.NET. I declare a session in page load to store the user ID and which will be empty by default.

When the user clicks login the login page appears and the user logs in and user ID is stored in the session.

When I return to the index page it disappears.

Here is my code:

if (!Page.IsPostBack)
{
    Session["UserID"] = "";
}

if (Session["UserID"] == "")
{
    HP_User.Text = "New User";
    HP_Login.Text = "login";
}
else
{
    HP_User.Text = "welcome ." + Session["UserID"].ToString() ;
    HP_Out.Visible = true;
    HP_Login.Visible = false;
}

Since your login page is a separate page from the page you're talking about, it won't be considered postback when the user is directed back to your page after logging in. So each time your user visits this page, their Session["UserID"] is being set back to "" . Try just:

if (!String.IsNullOrEmpty(Session["UserID"]))
{
    HP_User.Text = "New User";
    HP_Login.Text = "login";
}
else
{
    HP_User.Text = "welcome ." + Session["UserID"].ToString() ;
    HP_Out.Visible = true;
    HP_Login.Visible = false;
}

Try this:

if (!Page.IsPostBack)
{
    Session["UserID"] = "";

if (Session["UserID"] == "")
{
    HP_User.Text = "New User";
    HP_Login.Text = "login";
}
else
{
    HP_User.Text = "welcome ." + Session["UserID"].ToString() ;
    HP_Out.Visible = true;
    HP_Login.Visible = false;
}
}

Regards

Don't know if you are still needing this or not but would it not help to just check if the Session is empty or not ie

if (!Page.IsPostBack) 
{    
 if (String.IsNullOrEmpty(Session["UserID"]))
{
 Session["UserID"] = ""; 
}
} 

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