开发者

Session and Page.IsPostBack

开发者 https://www.devze.com 2023-02-28 12:24 出处:网络
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.

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开发者_C百科.

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 i.e

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

精彩评论

暂无评论...
验证码 换一张
取 消