如何在Asp.Net中将Session的值设置为没有成员资格的LoginName

本文关键字:成员 LoginName 设置 Asp Net Session 中将 | 更新日期: 2023-09-27 18:04:49

我有MasterRoot.MasterLoginPage.aspx

登录成功后,如何将"Session"的值设置为"HeadLoginName"。

Login.aspx.cs

protected void btnLogin_Click(object sender, EventArgs e) {
    UserClass user=new UserClass();
    user.LoginProcess(txtUserName.Text,txtPass.Text);
    if(user.loginsuccess) {
        Session["UserName"]=user.username.ToString();
    }
}

MasterRoot.Master.cs

protected void Page_Load(object sender, EventArgs e) {
    // Like this HeadLoginName.Text=Session["UserName"].ToString();
} 

如何在Asp.Net中将Session的值设置为没有成员资格的LoginName

母版页中的Load()事件在您分配会话["UserName"]之前执行,因此在用户单击登录后它是空的。您要么需要使用Response。重定向:重定向到某个页面并"刷新"一个页面,或者直接从内容页

为母版页上的标签赋值
if(user.loginsuccess) {
    Session["UserName"]=user.username.ToString();
   // Gets a reference to a Label control that not in a ContentPlaceHolder
   Label mpLabel = (Label) Master.FindControl("HeadLoginName");
   if(mpLabel != null)
      Label1.Text = user.username; 
}

阅读有关如何从内容页访问母版页和ASP中的事件的更多信息。. NET母版和内容页

如果你只是想分配会话值,没有任何异常,你可以这样做在母版页

HeadLoginName.Text=(Session["username"]==null)?"some value you like":Session["username"];

当用户成功登录时,你可以在子页面

中输入如下内容
 Session["username"]=usernametxt.Text;

那么该值将在您的母版页的页面回发中分配;