Understanding ViewState and FormData - asp.net

I just got started with ASP.NET MVC, and I suddenly asked myself: why does ASP.NET need ViewState in the first place? FormData is actually holding the state across postbacks. ViewState is only needed if the state of the control is changed, and that change is NOT included in FormData. For example, what if the event handler changed the control's font color?
Two questions:
For WebForms, is that the reason for the need of ViewState?
If yes, how can MVC "maintain a control's property which is NOT in FormData"?

MVC and WebForms are very different in this regard. The point of WebForms was to help ease WinFroms developers in to web development. For that reason the infrastructure of WebForms simulates statefullness whenever it can. ViewState is one of the ways this is implemented. Since the browser only posts back form fields, in WebForms the entire page is one big form and the entire page is posted to the server. The ViewState is a hidden field, which holds everything BUT the data in the inputs, selects, etc. which the browser posts by default.
On the other hand MVC does not try to simulate statefullness. It works more directly with HTTP and the basic rules of a stateless system. So when you post a form ONLY the data in the inputs, selects, etc. gets posted. Nothing else makes it back to the server.
This is why, if you want to return the same view after a post with the updated data, you have to refill the ViewModel with data like you did in the original get method. MVC does not take care of this for you like WebForms.

Regarding why View State in first place, your explanation is related. View State is used to persist state across Post Backs and mainly to handle properties updated programmatic for example page with label and button and you have event handler for the button that change the label front color to red , in the page load the controls initiate the label with default color however when the button click it change the label color to red and keep that change in the view state so if anything triggered post back then after loading the controls in the page load it sets the front color to the value already saved inside the viewstate
For more details please check the following link http://msdn.microsoft.com/en-us/library/ms972976.aspx#viewstate_topic3
MVC doesn't have viewstate, MVC is based on model binding so when a form is posted MVC framework read the httprequest parameters and try to create strongly typed object from that request and you can create your own model binder that tell the MVC how to read the http request

Related

knockout in asp.net web from master page

Good day.
I was using knockout in an asp.net web form master page. On master page i have an advanced search control completely with knockout. After selecting the search criteria by readio buttons, tabs and dropdowns, on clicking a search button redirect to a details page which is also inherited from the same master page.
I need to persists the selected view from the first page in the details page along with populating the search result.
But I'm unable to do it as an infant in knockout.
I guess if I can remove the binding and apply it again, it will be happen.(don't know I'm wrong or not).
Kindly advice me to get over this situation.
Thanks
Santhi
It sounds like you're doing a complete trip to the server between pages. In that case you'll need to store the state of your search box somehow before the redirect, and then load that state after the redirect. You have a couple ways to do this.
Using Cookies
You could serialize the state of your select control into a JSON string and store it in a cookie. When your search box loads, look for that cookie using JavaScript and if it exists, load the data into your search box.
Using the Query String
You could serialize the state of your select control into the query string, and load from that. This would be a little bit more reliable in case cookies are turned off on the user's browser.
Using Local Storage
If you're working in modern browsers and supporting HTML 5, you could use HTML 5 local storage to store the search state between postbacks. http://diveintohtml5.info/storage.html
Serializing your Model State
Take a look at this page of the Knockout JS documentation for more info on serializing your object graph. http://knockoutjs.com/documentation/json-data.html
I hope this helps!

How is the ViewState used to save a value in browser?

I set ASP.Net ViewState to off for a text box control, but the value for the name of the user is still there. Why is this so?
In a nutshell:
View state's purpose in life is simple: it's there to persist state across postbacks. (For an ASP.NET Web page, its state is the property values of the controls that make up its control hierarchy.) This begs the question, "What sort of state needs to be persisted?" To answer that question, let's start by looking at what state doesn't need to be persisted across postbacks. Recall that in the instantiation stage of the page life cycle, the control hierarchy is created and those properties that are specified in the declarative syntax are assigned. Since these declarative properties are automatically reassigned on each postback when the control hierarchy is constructed, there's no need to store these property values in the view state.
like balexandre already posted
ViewState cannot be modified by the browser, as the browser has no knowledge of what viewstate is. It's merely a snapshot of what was sent to the client and will be interrogated once the form is post back to the server.
Have a look at the following article to get a better understanding of what ViewState is
In a simple answer: Yes
But you should read all about View State as it's important to undertsand it and not thinking that things automagical work.
Understanding ASP.NET View State

What is all this stuff in ASP.NET HTML output?

Please see this:
VIEWSTATE" id="_VIEWSTATE" value="/wEPDwUKMTMzMTM1NTAzNA9kFgJmD2QWAgIDD2QWJgIDDw8WBB4LTmF2aWdhdGVVcmwFKGh0dHA6Ly93d3cubGVhcm5kZXZub3cuY29tL1Byb2R1Y3RzLmFzcHgeBFRleHQFCVN1YnNjcmliZWRkAgUPDxYCHwAFHWh0dHA6Ly9vbmxpbmUubGVhcm5kZXZub3cuY29tZGQCBw8PFgIfAAUnaHR0cDovL3d3dy5sZWFybmRldm5vdy5jb20vRGVmYXVsdC5hc3B4ZGQCCQ8PFgIfAAUoaHR0cDovL3d3dy5sZWFybmRldm5vdy5jb20vUHJvZHVjdHMuYXNweGRkAgsPDxYCHwAFJ2h0dHA6Ly93d3cubGVhcm5kZXZub3cuY29tL1NhbXBsZXMuYXNweGRkAg0PDxYCHwAFKWh0dHA6Ly93d3cubGVhcm5kZXZub3cuY29tL3N1YnNjcmliZS5hc3B4ZGQCDw8PFgIfAAUjaHR0cDovL3d3dy5sZWFybmRldm5vdy5jb20vRkFRLmFzcHhkZAIRDw8WAh8ABSxodHRwOi8v........ (it's 10 times bigger but I've removed it)
Is this HTML that ASP.NET produce? And does ASP.NET MVC do the same as well?
That is called ViewState.
ASP.NET MVC does not produce ViewState.
ASP.Net MVC does not produce viewstate, but that doesn't necessarily mean it's faster.
First of all, if you have that much viewstate in an ASP.Net webforms page you're probably doing something wrong. It's not that hard to avoid large viewstates in webforms.
Secondly, the things webforms puts into viewstate mostly substitutes for things mvc pages need to rebuild on each request. This tends to work in mvc's favor on public internet sites, where the bandwidth is both more expensive and slower than using additional server resources. For the private intranet on your company's LAN, it tends to favor webforms where upstream bandwidth from browser to web server is free, plentiful, and fast.
Web forms uses viewstate to maintain control state when you post back to the server. For instance, say you have a text box and a button on a web form. You type something in the text box and click the button. The button performs a post back to the server. When the page reloads, unless you cleared the text box yourself in server-side code, the text box would still contain whatever typed before you clicked the button.
What actually happened was that the data in the text box was stored in the hidden viewstate field and loaded into the text box again upon the page refreshing. The viewstate looks like a jumbled mess because it is base64 encoded. You can store things in the viewstate yourself manually also. In the page_load event of your page just do this:
this.ViewState["someVariable"] = "some value";
Now, if you did this on a blank web form, when you load the page you will see a viewstate field in the html like the one you pasted (except a lot smaller). If you copied the value from that hidden field and pasted it into a viewstate decoder (like this one) you would see someVariable with a value of "some value".
Now put a button on the form and in the button's click even do this:
Response.Write(this.ViewState["someVariable"].ToString());
You will see "some value" written out on the page. What you did was manually store something in the viewstate, it got rendered to the page in that hidden field, then that hidden field got posted back to the server and you read from it to display the data.
This is the primary functionality of web forms. MVC does not use viewstate. MVC relies on another technique known as model binding which would be out of the scope of your question. Google "asp.net mvc model binding" for more information on the way mvc maintains information across posts.
Slightly off-topic example of a viewstate joke:
I have a rather large community site called U413. I recently redesigned it to use ASP.net MVC 2.0. It's a community for programmers and they razz me all the time for using webforms. Well now that it doesn't use webforms I decided to play a little joke on them. MVC does not use viewstate but I went into a webform and generated a viewstate that contained some data and manually pasted the hidden field into my view in my MVC app.
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjkPFgIeE1U0MTNTZWNyZXRBY2Nlc3NLZXkFM2h0dHA6Ly93d3cudTQxMy5jb20vQ29udGVudC9VNDEzU2VjcmV0QWNjZXNzS2V5LmpwZ2RkpshYUvbSiUuE0YaYNBH0rvTGj4qEcquSqQeUs9ZpuIQ=" />
Already several people have gone snooping through the html source hoping to find little secrets or exploits and encountered this. They immediately decoded it and got a good laugh. Copy the value and paste it into the decoder I linked to earlier if you want to see.

ASP.Net viewstate questions on form postbacks

Let's assume I have a very simple form, with a submit button and a dropdown list. When I change the list entry and hit submit, at what stage in the postback processing does the viewstate reflect my changed list entry?
According to O'Reilly's Learning ASP.Net 3.5, there are two loads taking place-- one before form validation and another after (diagram on page 266 for those with a copy).
According to the diagram the viewstate is loaded during the first load stage, before the validation. I assume my changed dropdown is reflected at this point?
Also, according to the diagram, posted data is processed twice, both before and after validation. Could anyone elaborate a little more on this, and what form processing takes place at each point?
Thanks for the help. It's a little misty, what takes place when and I'm trying to clear it up a bit.
The viewstate is loaded after page initialization but before page load. Validation takes place just before the event triggers for the button that caused the validation.
ASP.NET Page Life Cycle Overview
Understanding ASP.NET View State
ASP.NET Validation in Depth

How to persist ViewState for reuse later?

Is it possible to save ViewState information, e.g. to session, so that when you navigate away from the page it is persisted somehow? Then when you return to that page you can reload the view state and the choices you've made are preserved.
Background
I have two pages, a report page, where you can pick data, do some filtering and sorting etc. and a chart-page, where the data you picked from the report page can be presented in different ways, with different choices for presentation.
If the user has tested different presentations, simply using the back-button could mean quite a few clicks before the user's back at the report page. I'd like a direct link to the report page.
Using QueryString to save control states is not an option.
I can't customize the ViewState storage for the whole application.
Yes, it's possible to store the Viewstate in something like a database. You just need to implement one of the viewstate providers. See here for an example using the SqlViewStateProvider.
Edit: Just re-read your post, and saw that you said you couldn't customize how the viewstate is stored for the whole application. If that's the case, you might want to look into storing it in a session. Scott Hanselman discusses that here.
Your link could automatically navigate back the required number of pages using JavaScript. Look at window.history, if you can count the number of pages forward you can navigate back that many.
The ViewState is already designed to persist the state of the user controls. If your user has made a selection and that selection is processed server side with a full page postback the new state of the controls will be saved in the ViewState (hidden input __VIEWSTATE).
If your report is using AJAX and partial page postbacks then you won't get the ViewState on the page anyway.
Just to clarify, the SQLViewstateProvider is NOT an application wide implementation. You have to create a class which inherits from the System.Web.UI.Page object and overrides the Save And Load viewstate methods of the Parent Page class. For each page that you want the viewstate to be saved on server side you then have to inherit from your newly created Page Template (Which in turn inherits and overrides the System.WEb.UI.Page class).
So it is applied on a per-page basis, not on an application-wide basis.
HEADS UP: Some controls might contain some client-side javascript code which may reference the viewstate on client-side (duh). If the viewstate is now stored on server-side you will get a null-reference exception (for instance, clicking a commandfield in a gridview). I'm working on a workaround for this problem, but unfortunately I do not have any concrete solution as of yet.
This is a bad idea, just use querystrings. I would be interested to know why they are not an option.

Resources