What is viewstate in asp.net - Part 3

In this video session, we will learn about
1. Stateless nature of HTTP protocol
2. How a webform is processed
3. What is ViewState
4. The role of ViewState in ASP.NET
5. Primary difference between ASP.NET Server controls and HTML controls

Web Applications work on HTTP protocol. HTTP protocol is a stateless protocol, meaning it does not retain state between user requests. Let's understand the stateless nature of the HTTP protocol with an example.

Create a new asp.net web application project. Drag and drop a TextBox and a Button control onto the webform. Change the Text property of the Button control to Click Me.

At this point, double click the button control, which should generate the event handler in the code behind file. Modify the code behind file, so the code in WebForm1 class looks as shown below. 
1. In the scope of WebForm1 class, we are creating an integer variable ClicksCount which is initialized to ZERO.
2. On the Page_Load() event handler, we are setting the Text property of TextBox1 to ZERO. We do this initialization, only, when the request is an initial GET request.
3. In the Button1_Click() event, we are incrementing the value of the ClicksCount by 1, and then assigning the value to the Text property of TextBox1.
public partial class WebForm1 : System.Web.UI.Page
{
    int ClicksCount = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            TextBox1.Text = "0";
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        ClicksCount = ClicksCount + 1;
        TextBox1.Text = ClicksCount.ToString();
    }
}

With this code in place, run the application, and click the Button. We expect the count to be increased every time we click the button. When you click it the first time, it gets incremented to 1. After that, no matter how many times you click it, the value stays at 1. This is because of the stateless nature of the web applications that work on HTTP protocol.



So what actually happens when you make a GET request for this WebForm1?
When we compile this project an assembly is generated. Since the name of the project is ViewStateDemo, the name of the assembly will be ViewStateDemo.dll. So when a request is made for WebForm1, The application's assembly(ViewStateDemo.dll) creates an instance (object), of WebForm1, initializes ClicksCount to ZERO, and set's the TextBox1.Text to ZERO. As this is the initial GET request, the Button1_Click() event will not be executed. At this point the web server, generates the HTML to respond to the request, and posts that response back to the browser. It then immediately destroys the instance of the WebForm1.

The browser receives the HTML, and we should now see textbox set to ZERO.

What happens when we click the Button on WebForm1?
When we click the Button, the WebForm1 gets posted to the server. This is a PostBack request, NOT A GET REQUEST. So, when the webform is posted back, a new instance of this webform is created again, initializing the ClicksCount variable to ZERO. This time, the code that is wrapped between IF(!ISPOSTBACK) block is not executed. Button1_Click() event gets executed as this is a PostBack event. ClicksCount is incremented from 0 to 1. The value is then assigned to the Text Property of TextBox1. Generates the HTML, sends it to client and destroys the webform.

At this Point, we should see the value increased to 1.

What happens when we click the Button on WebForm1 again?
When you click the button for the second time, the webform gets posted back again. A new instance of WebForm1 is created. ClicksCount initialized to ZERO. In the Button1_Click() event, the value gets incremented to 1 and assigned to TextBox1. HTML gets generated and sends it to client and destroys the webform.

So, no matter how many times you click the Button, the value of the TextBox, will not move beyond 1.

Now, let's see, how to preserve the state between requests using ViewState variables. Re-write the code in WebForm1, as shown below.
public partial class WebForm1 : System.Web.UI.Page
{
    int ClicksCount = 1;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            TextBox1.Text = "0";
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        if(ViewState["Clicks"] != null)
        {
            ClicksCount = (int)ViewState["Clicks"] + 1;
        }
        TextBox1.Text = ClicksCount.ToString(); ;
        ViewState["Clicks"] = ClicksCount;
    }
}



Click the Button now, and the value gets incremented every time we click. So how is this possible now. It's possible because, we are using the ViewState variable Clicks to preserve the data between requests. The ViewState data, travels with every request and response between the client and the web server.

Now, let's try to achieve the same behaviour, without explicitly storing data in a ViewState variable. Modify the WebForm1 code as shown below.
public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            TextBox1.Text = "0";
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        int ClicksCount = Convert.ToInt32(TextBox1.Text) + 1;
        TextBox1.Text = ClicksCount.ToString(); 
    }
}

Upon clicking the Button, the value gets incremented correctly as expected. This is possible because, TextBox1 is an asp.net server control, that uses viewstate internally, to preserve data across postbacks.

Because Web forms have very short lifetimes, ASP.NET takes special steps to preserve the data entered in the controls on a Web form. Data entered in controls is sent with each request and restored to controls in Page_Init. The data in these controls is then available in the Page_Load(), Button_Click(), and many more events, that occur after Page_Init() event. We will discuss about, all the events in the life cycle of a webform and the order in which they occur in a later video session.

On the other hand the HTML controls, do not retain state across post backs. Only ASP.NET server controls retains state. To prove this
1. Add a new webform to the web application project
2. Drag and Drop Input(Text) control from the HTML tab, in the ToolBox
3. Drag and Drop TextBox control from the Standard tab, in the ToolBox
4. Finally drag and drop a button
5. Set the newly added webform as the start page by right clicking on it, in the solution explorer
6. Run the project, by pressing CTRL + F5
7. Type "TEST" into both the controls (ASP.NET TextBox and the HTML TextBox), and press the button
8. You should see that, the value in the ASP.NET TextBox is preserved across postback, but not the value in the standard HTML textbox

An HTML control can be converted in ASP.NET server control, by adding runat="server" attribute in the HTML source as shown below.
<input id="Text1" runat = "server" type="text" />

Now, if you type TEST and click the button, both controls now retain state across postback.

ViewState data is serialized into base64-encoded strings, and is stored in Hidden input field __ViewState. To view this hidden input field, right click on the browser and select "View Page Source" for google chrome. In internet explorer, right click and select "View Source"

30 comments:

  1. i tried the second code without viewstate, but txtbox as server control . but as i click my button , the value is 1 and is not incrementing. do i have to change any property of textbox?

    ReplyDelete
    Replies
    1. Hi Sneha, there is not need to change any property of the textbox. If you are using an asp.net textbox control, it should retain it's viewstate automatically. Please watch video Part 3 from asp.net video tutorial at the following link. That should solve the issue you are facing.
      ASP.NET Video Tutorial

      Delete
  2. Dear Sir,
    Could you please add LINQ and ENTITY FRAMEWORK TUTORIALs soon? I learned lot from your tutorials and it was the BEST I could find from internet. Super of JOB SIR.

    ReplyDelete
  3. if i need to disable asp textbox view state Its not working!

    ReplyDelete
  4. i have a question
    how can i set textValue to htmlControl(textField)?
    thanks in advance :D

    ReplyDelete
    Replies
    1. You have to use jquery ajax to set the value of Html Control(textField) otherwise you have to make server Control.

      Delete
  5. textbox control is retaining it's value even when view state mode for the control is disabled.what's the reason for this and if view state does not have any effect on the control when the mode is disabled then why this property is available for the control.

    ReplyDelete
    Replies
    1. I believe this behaviour is due to inheritance nature of controls.Just give a thought All controls(Textbox,Labels etc) inherits webcontrol class and webcontrol class inherits control class.The signature of LoadViewState and Save Viewstate is in Control which is overridden by webcontrol, Thus TextBox gets this behaviour in legacy (though it is of no use since controls like textbox implements IPostBackDataHandler due to which the state of data is maintained accross postbacks no matter EnableViewState is set to true or false)......I think since this behaviour is not impacting the functionality of textbox microsoft didn't bother to seperate this functionality).

      Delete
  6. Hi,
    we can increment the counter with the help of
    static int but as you mention in article that each and every request
    create a new instance of Webform and object is destroyed after response then how it possible with static int variable. please elaborate...

    Thanks

    ReplyDelete
  7. ganesh

    hi, sir

    i am trying the first code with viewstate but it's not increment text value.how to solve this one

    ReplyDelete
  8. Hello Sir,
    Please suggest me one think,regarding asp.net in c# .. whenever we take button from tool box to design. All running ok. But when ever i double click on button then there is no window coding is find.. but i will ok to see the viewcode by right click on button. But my issue is that .. why protected void button1_Click(object sender,eventarg e) not getting in view code?

    ReplyDelete
  9. Hi Sir,
    Your tutorials are helping me very much to expertise in .net skills,your valuable effort is appreciated.

    ReplyDelete
  10. what happen if i'll make the "static int ClicksCount = 0;"....

    ReplyDelete
  11. Sir,
    Please tell me
    why can not use string variable instead of viewstate like store "Rakesh" in viewstate

    reply very urgent.

    ReplyDelete
  12. I got VS 2013 express initial code without viewstate is reporting 0 all the time wonder what I may be doing wrong copied exact same code

    ReplyDelete
  13. Not Showing any value in TextBox why??

    ReplyDelete
  14. For those whose viewstate value is reporting 0 all the time they have copied the code from this blog and directly pasted on their VS you should first click the button on your webform then the button click event will be generated and then inside that event you should write your code don't copy paste that's the reason the value is always coming up with 0

    ReplyDelete
  15. How can i use html control's in the C# coding

    ReplyDelete
  16. Hello sir i am beginner can you help me.i am facing the following problem ,,

    CS1061: 'ASP.webform1_aspx' does not contain a definition for 'TextBox1_TextChanged' and no extension method 'TextBox1_TextChanged' accepting a first argument of type 'ASP.webform1_aspx' could be found (are you missing a using directive or an assembly reference?)

    ReplyDelete
  17. The toolbox is empty. How do I get it to work. I get "No results found" whenever I search for anything.

    ReplyDelete
  18. Hello Venkat ,
    It is one of the great Blog to learn about ASP.net ,Which ever i have seen,it will help the Beginners to learn the concepts.

    ReplyDelete
  19. runserver for html text not working

    ReplyDelete
  20. Hi, where can I able to get your asp.net tutorial for beginners full text version like PDF. If u are already have it can u please send that text version or at least send me the link.

    ReplyDelete
  21. Hello Sir,What is the default value of ViewState["Clicks"]

    ReplyDelete
  22. super sir......
    But some doubt
    int ClickCounts = Convert.ToInt32(TextBox1.Text)+1;
    TextBox1.Text = ClickCounts.ToString();
    this is ok for the asp.net control like textbox

    If it is html input(text) then how can i use viewstate because viewstate common for all the web applications.Then how can i hold/preserve the text value for html control.

    ReplyDelete
  23. Bro u have raised the text_Changed event ,In this senario u dont need it to viewstate preservation or holding raise the Click event for the button and Initialise the varialble like
    int ClickCounts
    protected void Button-Clicked(Object sender,Eventargs e)
    {
    ClickCounts = Convert.Int32(TextBox1.Text)+1;
    TextBox1.Text = ClickCounts.ToString();

    ReplyDelete
  24. Thanks vancket sir to make a blog for beginnerand intermediate.

    ReplyDelete
  25. Sir I tried code but value is not incremented by 1 why?

    ReplyDelete

It would be great if you can help share these free resources