I have read that viewstate is not there in asp.net MVC application. I am doing model validation. Now if i have two text boxes on my page,and i am doing required filed validation for both of them in model. This validation is done on server side on click of a button. I will fill one text box and click on submit button. It does the validation and returns the result saying second field is required. At this time value of the first text box is retained. So can you tell me how this text box is retaining the value even after postback?
5 Answers
There is no "postback". There's just a post.
- Server returns HTML.
- Browser renders it.
- User POSTs crap data.
- All of the user's submitted data is saved in the
Controller.ModelStatecollection. - Each
ModelStateentry has itsErrorsproperty set if there is a validation error. - Server looks at crap data. Returns page same as (1) except that it includes user's submitted data, good or bad, and validation errors for the crap data.
- Browser renders that.
When you call, say, Html.TextBox("someName", someValue) then the text box will contain someValue unless there's a ModelState key for "someName", in which case the value from ModelState is used instead. This is how the default data (if any) is displayed originally, but the user's data is displayed after an error.
3 Comments
ModelState is used only in the time between the POST and your app's response to it. Then it is forgotten.Read about ModelState. When you post http form, values are stored in ModelState object and reused when you generate form again using html helpers (Html.Label, Html.Hidden, Html.TextBox).
- Form is shown using Html.TextBox().
- User enters value first time.
- Form is posted.
- ModelState object holds textbox value.
- Form is shown second time using Html.TextBox() again. Method looks into ModelState and sets its value again as it was posted first time. Even if you provide new value, it will be searched in ModelState object.
Comments
Enabling view state is actually supposed to retain values of the controls if you are posting back to the same page