views:

106

answers:

5

Hi,

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?

+7  A: 

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.

Craig Stuntz
User Post crap data - except if it is the developer :)
Aristos
thanks all for the answers. Howe does model state internally stores the values between post? does it uses tempdata or any other method???
Shetty
It doesn't. `ModelState` is used only in the time between the `POST` and your app's response to it. Then it is forgotten.
Craig Stuntz
+2  A: 

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.
LukLed
A: 

The value of the textbox is bound to the Model value.

Upon validation failure the page is redisplayed with it's Model in the state it was when the submitted (i.e. with a value for the first textbox) and any ModelState Errors added.

No viewstate coming in to play ;-)

Kindness,

Dan

Daniel Elliott
A: 

Enabling view state is actually supposed to retain values of the controls if you are posting back to the same page

Lina
+1  A: 

View is rendered using Model. On failed validation if you pass the same model (with ModelState errors) to the view it will repopulate the same view with extra Validation messages which are rendered using ModelState Errors.

Amitabh