Understanding PostBack Event and ViewState in Asp.Net

In this tutorial I will cover two fundamental concepts in ASP.NET Web forms applications: PostBack and ViewState. These two concepts are essential to understanding how Web Forms work.

Let’s explore these concepts with an example. Please open Visual Studio and follow the steps below to create our example:

  1. Create a new ASP.NET Empty Web Application (Visual C#), and name it ViewStatePostBack,
  2. Add a new Web Form to the project, and name it Universities.

1

Lets’ create a form that we can use to create new university items. We will use a table for this purpose. Let’s add the table by using the Table menu as shown in the image below:

2

Please enter the following values as indicated with arrow in the following image, then press OK button.

3

Then, you will have the table inserted on the page. Please note that the table inserted is an HTML table, NOT an ASP.NET table. The definition of the table does not involve any ASP.NET tags or attributes, it is a pure html markup.

4

Let’s add the web controls to complete our form, it should look like the following image. It is important that you use the Source window and type the necessary markup instead of dragging and dropping the controls. This will help you get familiar with the asp.net tags and also html markup. Later, if you need to learn some client-side programming like JavaScript or jQuery, it is better that you are comfortable working in the Source view not Design view. Once you get used to it, you will realize that building the web forms for your pages is faster when using the Source view rather than the Design view.

5

Now, the dropdownlist is empty, it has no items inserted yet. We will add some items, i.e., Country items to the dropdownlist in codebehind. Please switch to the CodeBehind file of Universities.aspx page, and add the following code:

6

We wrote a method (or a function), called BindCountries. It returns no values this is why its return type is defined as void. This method adds three countries to the dropdownlist. If we run our application now, do you think the countries will be added to the dropdowlist? Of course, no. This is because we never invoked the BindCountries method. A method will be executed only if is called somewhere in the program. Let’s call BindCountries method within Page_Load method, in this way, the countries will be added to the dropdownlist when the page is loaded for the first time.

7

Now, please run the application. Please test the application by writing a university name to the textbox and then clicking the submit button. You will see that after each click, the items in the dropdownlist will be duplicated:

8

First, when you clicked the button, the page will be submitted to ASP.NET server for processing. This is because, your browser (the client-side) is not capable of interpreting this ASP.NET event and therefore the details of this event should be sent to the ASP.NET server for processing. The ASP.NET server then can interpret the request and create an HTML output and send it back to your browser. That is why, if you view the source of your Default.aspx page, you will only see HTML tags. For example, if you have an ASP.NET Label control, the server will convert the label to a <span> tag and send it to your browser. Thus, PostBack is a round-trip process, initiated from your browser and completed at your browser.

I created an animation to illustrate this process, please view the ANIMATION.

Then, why is there a duplication of the items in the dropdownlist after each PostBack event occurs? It is because the server knows the already existing items in the list, and add the same items again because BindCountries() method will be called again inside the Page_Load method. How come does the server know the items already created in previous calls? Normally, the dropdownlist items are supposed to be re-created from scratch each time Page_Load is executed with PostBack request, right?

The reason behind the duplication is the ViewState. ViewState is a technique in ASP.NET to store all the temporary information about a page – like what options are available and currently chosen in each select box. So, ViewState stores the information about the current web controls on your web form. The information is serialized and kept in a hidden variable, called _VIEWSTATE. The _VIEWSTATE variable is always posted back to the server whenever there is a server round trip (PostBack event). This is how the server is able to access the values of the controls sent from the client. If there is any change to the values of the controls (adding an item to a dropdownlist) in the server code, that change is made in the view state and sent back to the browser.

In this tutorial I will not go into depths of ViewState and ASP.NET Page Life Cycle, since it has MANY details, as you can see the illustration below:

Here are couple of useful resources, if you want to have an indepth understanding in PostBack & ViewState:

Let’s go back to our example. We can prevent duplication of Country list in three ways in our scenario. The first option is using IsPostBack property of Page class:

9

IsPostBack is a Boolean-type property of the Page class and its value is true if the server receives a request as a result of a postback event such as button click. Otherwise, its value will be false, for example when the page is requested for the first time. In Page_Load event, we can write an IF condition to allow the execution of BindCountries() method only if it is NOT a PostBack request. In this way, clicking submit button will not invoke BindCountries method, therefore, no duplication of countries will occur. Actually, whenever you want to bind a data to a control in Page_Load, please make sure you include IF condition checking if it is a postback or not. Otherwise, you will do unnecessary calls to database and create redundant data sets.

The second approach, which is not recommended, would be clearing the existing items in the dropdownlist before binding the new items. This is not recommended because it makes the process more complicated and create extra work for the server. You should notice that your selection will be lost when the button is clicked. Please think about the reason yourself. Also think about what would happen if the ViewState were read and loaded by the server after Page_Load event?

10

In another approach, we can turn on/off ViewState per web control. Let’s disable ViewState for the dropdownlist. For this, we need to set EnableViewState to false for the dropdownlist:

11

Similarly, when you click the button, your selection will be lost, although you will see the correct list of countries. This is because, ViewState was storing selection information and since it is disabled, this information does not exist anymore.

How about we include Page.IsPostBack condition in CodeBehind while still keeping the ViewState disabled for the dropdownlist:

12

When you click the button, the dropdownlist will be cleared (see the following image). There are two reasons for this: first, since ViewState is disabled, the server has no idea about the existing items in the dropdownlist; second, we did not  populate items for the dropdownlist in the Page_Load if there is a PostBack.

13

Let’s try several more things. Let’s add a label (lbl_Output) next to the button:

14

Then, let’s double click on the button and add the following code to the click event:

15

Please run the application, choose a country from the list and click the button. You will get the following error:

16

This is because you are trying to access a list item that does not exist (NULL). It is NULL because, when we click the button a request is sent to Server to interpret the click event, Server recreates the page for you but cannot know or remember the current state of the web form. Therefore, it will build the page with empty dropdownlist. Then, it will execute your button click event, where you will try to access the dropdownlist which is empty.

Would it matter if we remove drp_Country.Items.Clear() line? Definitely not! It is because BindCountries() method will never be called with PostBack events on the server.

How about if we remove the Page.IsPostBack check:

17

Try to choose Turkey and press the button, you will see USA is printed on the label. But, why? I will leave it to you to think and answer.

18

2 thoughts on “Understanding PostBack Event and ViewState in Asp.Net

  1. Pingback: Standard Asp.Net Web Controls: TextBox, Label, Button, Checkbox, RadioButton, LinkButton | Web Applications with Asp.Net Entity Framework

Leave a comment