本文介绍了如何将会话值从内容页面传输到母版页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图通过使用下面的代码将会话值传递给我的母版页的标签,但是来自内容页面的数据传输但是进入母版页。显示空值异常。
代码:
I was trying to pass a session value to label of my master page by using below code, but data from content page transfer but getting in master page. show null value exception.
Code:
<telerik:RadTextBox ID="UserName" runat="server"></telerik:RadTextBox>
<telerik:RadTextBox ID="Password" runat="server" TextMode="Password"></telerik:RadTextBox>
<telerik:RadButton ID="Submit" runat="server" Text="Submit" ></telerik:RadButton>
aspx.cs代码
Code of aspx.cs
protected void Submit_Click(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection(constr);
con.Open();
MySqlCommand cmd = new MySqlCommand("select COUNT(*)FROM User_table WHERE UserId='" + UserName.Text+ "' and Password='" +Password.Text+ "'");
cmd.Connection = con;
int OBJ = Convert.ToInt32(cmd.ExecuteScalar());
if (OBJ > 0)
{
Session["UserId"] = UserName.Text.Trim();
Response.Redirect("Default.aspx");
Label1.Text=Session["UserId"].ToString();
}
else
{
Label1.Text = "Invalid username or password";
this.Label1.ForeColor = Color.Red;
}
}
母版页代码
Master Page Code
if (Session["UserId"] !=null)
{
Label1.Text = "Welcome :" + Session["UserId"].ToString();
}
else
{
Response.Redirect("Login.aspx");
}
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 12: if (Session["UserId"] !=null)
Line 13: {
Line 14: Label1.Text = "Welcome :" + Session["UserId"].ToString();
Line 15:
Line 16: }
推荐答案
protected void Session_Start(object sender, EventArgs e)
{
Session["UserId"] = "";
}
然后在母版页内查看
then inside the master page , check
if (Session["UserId"] == "")
{
Response.Redirect("Login.aspx");
}
else
{
Label1.Text = "Welcome :" + Session["UserId"].ToString();
}
另一种解决方案是,这里我认为你是在使用同一个登录页面的母版页,它是在你设置会话变量之前加载的,这就是为什么得到错误,更改登录页面的母版页
谢谢
Another solution is that , here i think you are you are using the same master page for Login page also , it is loading before you set session variable thats why getting error , change master page for login page
Thanks
这篇关于如何将会话值从内容页面传输到母版页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!