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 ASP.NET New Website](http://lh4.ggpht.com/-U0Fn7iu-j6M/TeMcyfZ_RdI/AAAAAAAAAZU/BkPI9Om6oqU/image%25255B6%25255D.png?imgmax=800)
Now design a Default.aspx page as shown below -
![Sample ASP.NET Form Sample ASP.NET Form](http://lh3.ggpht.com/--IK3badAyM4/TeMczGffq6I/AAAAAAAAAZY/sr37-QL6HZQ/clip_image002%25255B5%25255D.jpg?imgmax=800)
Add a User Control with the name 'CustomersData' to display all the customers in a Grid from Northwind Database as shown below -
![image image](http://lh4.ggpht.com/-VO608dlrQ0E/TeMc8QOfAiI/AAAAAAAAAZc/Zf2k-pE6oLM/image%25255B12%25255D.png?imgmax=800)
Add this user control in our Default.aspx page. Now run the Default.aspx page and view the page source as shown below -
![clip_image002[6] clip_image002[6]](http://lh3.ggpht.com/-zo29HGBpHt0/TeMc9J6vybI/AAAAAAAAAZg/rdh0-tTYJQo/clip_image002%25255B6%25255D%25255B2%25255D.jpg?imgmax=800)
We will now disable the view state at Page level as well as Control level.
![viewstate-controlstate viewstate-controlstate](http://lh5.ggpht.com/-kMsiQNG5M18/TeMc9-R-z2I/AAAAAAAAAZk/C5WpuZq0lJE/viewstate-controlstate%25255B4%25255D.png?imgmax=800)
Re-run Default.aspx page and view the code.
![granular view state granular view state](http://lh4.ggpht.com/-DQgvivdfnfE/TeMc-h92LYI/AAAAAAAAAZo/cUaOiG4lZZE/image%25255B15%25255D.png?imgmax=800)
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 -
![viewstatemode viewstatemode](http://lh5.ggpht.com/-s3jUkna1Q3c/TeMc_DDlR8I/AAAAAAAAAZs/bj4_ctGL96I/image%25255B18%25255D.png?imgmax=800)
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
Tweet
No comments:
Post a Comment