Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET private member field loses value on postback

Consider the following code:

    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);            
        }
}

In this code, when I am declaring 'username' as private, it is initialized to null after subsequent post backs.

Why?

What is the secret?

like image 883
user366312 Avatar asked Aug 21 '09 19:08

user366312


2 Answers

Because ASP.NET is stateless meaning it does not keep it state from post back to postback. Save the user to the viewstate, session, or application to see it on postback to postback.

#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
like image 109
David Basarab Avatar answered Oct 29 '22 07:10

David Basarab


Every time you do any postback, even for "simple" things like button click events, you're working with a new instance of the page class. That's ASP.Net 101.

like image 37
Joel Coehoorn Avatar answered Oct 29 '22 06:10

Joel Coehoorn