Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

view state in ASP.NET MVC Application

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?

like image 473
Shetty Avatar asked Nov 24 '25 15:11

Shetty


2 Answers

There is no "postback". There's just a post.

  1. Server returns HTML.
  2. Browser renders it.
  3. User POSTs crap data.
  4. All of the user's submitted data is saved in the Controller.ModelState collection.
  5. Each ModelState entry has its Errors property set if there is a validation error.
  6. 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.
  7. 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.

like image 62
Craig Stuntz Avatar answered Nov 27 '25 09:11

Craig Stuntz


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).

  1. Form is shown using Html.TextBox().
  2. User enters value first time.
  3. Form is posted.
  4. ModelState object holds textbox value.
  5. 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.
like image 26
LukLed Avatar answered Nov 27 '25 09:11

LukLed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!