ASP.NET私有成员字段在回发时丢失了值

前端之家收集整理的这篇文章主要介绍了ASP.NET私有成员字段在回发时丢失了值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
请考虑以下代码
public partial class TeacherControlPanel : System.Web.UI.Page
    {
        protected string username = string.Empty;

        protected void Page_Load(object sender,EventArgs e)
        {
            username = (string)Request.QueryString["username"];

            Ice_Web_Portal.BO.Teacher teacher = Ice_Web_Portal.BO.Teacher.GetTeacherByUsername(username);

            if (teacher != null)
            {
                labUsername.Text = username;
                labName.Text = teacher.TeacherName;
                labTeacherCode.Text = teacher.TeacherCode;

                Dept dept = teacher.Department;

                if (dept != null)
                {
                    labDepartment.Text = dept.DeptName;
                }
            }
            else
            {
                //labErrorMessage.Text = "No teacher found";
            }
        }

        protected void btnSendMail_Click(object sender,EventArgs e)
        {
            Response.Redirect(@"~/Teacher/TeacherComposeMail.aspx?username=mahabub" + username);            
        }
}

在此代码中,当我将’username’声明为private时,在后续回发后将其初始化为null.

为什么?

秘密是什么?

解决方法

因为ASP.NET是无状态的,这意味着它不会使其从发回到回发状态.将用户保存到视图状态,会话或应用程序,以便在回发时查看回发.
#region UserName
public string UserName
{
    get
    {
        if (this.ViewState["UserName"] == null)
            return string.Empty;

        return (string)this.ViewState["UserName"];
    }
    set { this.ViewState["UserName"] = value; }
}
#endregion

猜你在找的asp.Net相关文章