请考虑以下代码:
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); } }@H_404_4@在此代码中,当我将’username’声明为private时,在后续回发后将其初始化为null. @H_404_4@为什么? @H_404_4@秘密是什么?
解决方法
因为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