State Management

The variables get forgotten while the page reloads. You can save their values with the following state management techniques:

    On server side:

·        Application variable

·        Session variable

·        Profiles

 

    On client side:

·        Cookies

·        Hidden Fields

·        Query Strings

·        State View

·        Control State

 

 

 

Session and Application variables

 

Default.aspx

 

   protected void Page_Load(object sender, EventArgs e)

    {

 

        string s = Application["zm1"].ToString();

        int z = Convert.ToInt32(s);

        if (!IsPostBack)

           z++;

        s = Convert.ToString(z);

        Application["zm1"] = s;

 

        TextBox1.Text = Application["zm1"].ToString();

 

 

        string s2 = Session["zm2"].ToString();

        int z2 = Convert.ToInt32(s2);

      

            z2++;

        s2 = Convert.ToString(z2);

        Session["zm2"] = s2;

      

        TextBox2.Text = Session["zm2"].ToString();

 

    }

 

 

Global.asax

<%@ Application Language="C#" %>

 

<script runat="server">

 

    void Application_Start(object sender, EventArgs e)

    {

        // Code that runs on application startup

        Application.Add("zm1", 1);

 

    }

   

    void Application_End(object sender, EventArgs e)

    {

        //  Code that runs on application shutdown

 

    }

       

    void Application_Error(object sender, EventArgs e)

    {

        // Code that runs when an unhandled error occurs

 

    }

 

    void Session_Start(object sender, EventArgs e)

    {

        // Code that runs when a new session is started

        Session.Add("zm2", 1);

 

    }

 

    void Session_End(object sender, EventArgs e)

    {

        // Code that runs when a session ends.

        // Note: The Session_End event is raised only when the sessionstate mode

        // is set to InProc in the Web.config file. If session mode is set to StateServer

        // or SQLServer, the event is not raised.

 

    }

      

</script>

 

 

Profiles

Add to web.config under the <system.web> section:

 

  <anonymousIdentification enabled="true"/>

    <profile>

      <properties>

        <add name="Name" allowAnonymous="true" />

        <add name="UserName" allowAnonymous="true" />

        <add name="FirstVisit" type="System.DateTime" allowAnonymous="true" />

        <add name="SecondVisit" type="System.DateTime" allowAnonymous="true" />

      </properties>

    </profile>

  

In Default.aspx.cs:

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        // Check if the user's name is defined, and greet him

        if (Profile.UserName.Length > 0)

        Label1.Text = "Welcome, " + Profile.UserName + "! ";

 

        // Define the first visit time if necessary

        if (Profile.FirstVisit.Year < 1900)

            Profile.FirstVisit = DateTime.Now;

    }

   

    protected void Button1_Click(object sender, EventArgs e)

    {

         Profile.UserName = TextBox1.Text;

    }

}

 

 

Cookies

    protected void Page_Load(object sender, EventArgs e)

    {

        int clicks;

        if (Request.Cookies["clicks"] != null)

            clicks = Convert.ToInt32(Request.Cookies["clicks"].Value) + 1;

        else

            clicks = 1;

        // Define the cookie for the next visit

        Response.Cookies["clicks"].Value = clicks.ToString();

        TextBox1.Text = clicks.ToString();
   }

    protected void Button8_Click(object sender, EventArgs e)

    {

        HttpCookie cx = new HttpCookie("pies", "szarik");

        cx.Expires = DateTime.Now.AddDays(7);

        Response.Cookies.Add(cx);

        Response.Cookies["kot"].Value = "mruczek";

        Response.Cookies["kot"].Expires = DateTime.Now.AddDays(7);

    }

   

    protected void Button9_Click(object sender, EventArgs e)

    {

        string s = Request.Cookies["kot"].Value;

        Label1.Text = s;

    }

 

 

 

 

 

You typically can store up to 20 cookies per site (depending on browser), and each cookie can be up to 4 KB in length. To work-around is to store multiple values in a cookie:

 

Response.Cookies["YourDog "]["LastVisit"].Value = DateTime.Now.ToString();

Response.Cookies["YourDog "]["name"].Value = "chic";

Response.Cookies["YourDog "]["color"].Value = "black";

Response.Cookies["YourDog "].Expires = DateTime.Now.AddDays(14);

 

 

 

Hidden Fields 

    protected void Page_Load(object sender, EventArgs e)

    {      

        int clicks1;

        int.TryParse(HiddenField1.Value, out clicks1);

        clicks1++;

        HiddenField1.Value = clicks1.ToString();

        Label1.Text = "HiddenField clicks: " + HiddenField1.Value;
    }

 

 

Query Strings 

    protected void Page_Load(object sender, EventArgs e)

    {

        int queryClicks;

        if (Request.QueryString["clicks"] != null)

            queryClicks = int.Parse(Request.QueryString["clicks"]) + 1;

        else

            queryClicks = 1;

        // Define the query string in the hyperlink

        HyperLink1.NavigateUrl += "?clicks=" + queryClicks.ToString();

        TextBox2.Text = queryClicks.ToString();
   }

  

Switching between pages loses all Hidden Field information but Cookies are preserved.

 

 

 

ViewState

 

If you click a button to submit an ASP.NET page, the page retains all its values (e.g. textboxes) and settings after it reappears. This is implemented by a client-side state management technique called ViewState. The code sample shows how view state adds data as a hidden field within a Web page’s HTML (in the same form values of other fields are preserved):

 

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTIxNDIyOTM0Mg9kFgICAw9kFgICAQ8PFgIeBFRleHQFEzQvNS8yMDA2IDE6Mzc6MTEgUE1kZGROWHn/rt75XF/pMGnqjqHlH66cdw==" />

 

View state is enabled by default for every control. To make the page reload faster, you can disable it by setting the EnableViewState property for each Web control to False.

 

 

You can also add and retrieve custom values with ViewState, as shown below:

 

public partial class _Default : System.Web.UI.Page

{

    [Serializable]

    public class dog

    {

        public int size;

        public string name;

 

        public dog(int size, string name)

        {

            this.size = size;

            this.name = name;

        }

    }

 

    dog dog1;

 

    protected void Page_Load(object sender, EventArgs e)

    {

        dog1 = new dog(15, "chic");

 

        if (ViewState["YourDog"] != null)

        {

            dog1 = (dog)ViewState["YourDog"];

            dog1.size++;

            dog1.name += dog1.name.Substring(3, 1);

        }

        else

        {  

            ViewState.Add("YourDog",dog1);

        }

      

        ViewState["YourDog"] = dog1;

        TextBox1.Text = dog1.size.ToString();

        TextBox2.Text = dog1.name;  

    }

 

    protected void Button1_Click(object sender, EventArgs e)

    { 

    }

}

 

 

That’s how much you can put into a (very long) View State:

 

    protected void Button2_Click(object sender, EventArgs e)

    {

        VS []vs = new VS[100];

        List<VS> A = new List<VS>();

        for (int i = 0; i < 100; i++)

        {

            vs[i] = new VS();

            vs[i].vsName = "Ala Ma Asa nr " + i.ToString();

            vs[i].vsValue = 10*i;

            A.Add(vs[i]);

        }

 

 

        ViewState.Add("A", A);

    }

 

    protected void Button3_Click(object sender, EventArgs e)

    {

        List<VS> A = new List<VS>();

      

        A = (List<VS>) ViewState["A"];

        foreach (VS v in A)

        {

            Label1.Text += v.vsName + " " + v.vsValue.ToString() + "   ";

 

        }

     

    }