Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I turn off viewstate for good?

Coming from a PHP background I love using clean URLs to grab data from one service to another.

However, on some of my ASP.NET projects I get the horrible ViewState parameter in my URLs.

Is there a way to turn this off globally?

What affect will this have on my ASP.NET app?

like image 543
Jon Winstanley Avatar asked Mar 15 '09 07:03

Jon Winstanley


People also ask

What happens when ViewState is disabled?

If you disable ViewState, and a page needs it, the page will no longer work.

Does ViewState affect performance?

To accomplish our tasks, we use ViewState a lot, but as we know, it doesn't come free - it has a performance overhead. The ViewState is stored on the page in the form of a hidden variable. Its always advised to use the ViewState as little as possible. We also have other ways to reduce the performance overhead.

Why do we use ViewState?

View state is used automatically by the ASP.NET page framework to persist information that must be preserved between postbacks. This information includes any non-default values of controls. You can also use view state to store application data that is specific to a page.


2 Answers

You can turn off viewstate for the whole site like this:

    <system.web>
<pages enableViewState="false" />

That said, you shouldn't be getting it on the url. ViewState is a hidden field that is sent to the server with a postback (which normally uses post). It keeps the state of the controls when the page was rendered to the client, sending it with each postback. If it works for the application you could switch to use post instead (the problem form is surely using get), if not take a look at Jon's answer.

Check this link for more information on how the viewstate fits into the asp.net life cycle: http://msdn.microsoft.com/en-us/library/ms972976.aspx.

like image 199
eglasius Avatar answered Sep 27 '22 22:09

eglasius


I had a similar question when writing the Reputation Tracker.

I don't know how you do it globally other than to just never use a form with runat="server" set, which is more to do with discipline than a setting. In particular, if you have runat="server" set on a form I believe you'll always get a viewstate parameter, even if you've turned it off everywhere so you don't get any values. That was my experience, anyway.

Obviously this limits you somewhat, but I've found that using the HTML server controls (instead of the ASP.NET controls) for appropriate parts of ASP.NET can make life a lot simpler to understand.

like image 37
Jon Skeet Avatar answered Sep 28 '22 00:09

Jon Skeet