ASP.NET 4 Granular View State

In this post, we will see how to control a view state at Page level as well as Control level. In ASP.NET 4.0, Microsoft has provided a property called 'ViewStateMode' at control level. Now you can turn OFF the View state at Page level and turn ON viewstate at Control level as per your requirements.

Note: In ASP.NET 3.5, when you disable view state at web application level from your web.config file, you cannot enable it at control or page level.

So let's create a simple web site as shown below -

ASP.NET New Website

Now design a Default.aspx page as shown below -

Sample ASP.NET Form

Add a User Control with the name 'CustomersData' to display all the customers in a Grid from Northwind Database as shown below -


Add this user control in our Default.aspx page. Now run the Default.aspx page and view the page source as shown below -


We will now disable the view state at Page level as well as Control level.


Re-run Default.aspx page and view the code.

granular view state

Observe the difference in the previous view state and this view state.

Even if view state of the Page is disabled, you can enable it at control level by using 'ViewStateMode' property at control level as shown below -


The above code will enable the view state for a Textbox 'txtCustomerName' even if the Viewstate is disabled at page level.

Download the source code

Will you give this article a +1 ? Thanks in advance

No comments: