Why the view doesn’t display the new values set in the post back method

In MVC, when you post back any changes, it’s recommended that you follow the PRG (Post-Redirect-Get) pattern to the View page. However, if you want to display the same model data back in the same request, there might be something you have to do.

Say if you have Edit method handles both Create and Update request, and you have a @Html.HiddenFor(m=>m.Id) in your view so that the update method knows which record to update:

 if( model.Id == 0 )
{
    int newId = InsertNewToDataBase( model );
   model.Id = newId; // <= this will not work
}
else
   UpdateDataBase(model);

return View(model);

After a new record is created, you want to set the new Id to the model so that the view will pick it up for the following edit request to work. No, this doesn’t work, @Html.HiddenFor(m=>m.Id) will still give you a zero.

Why is that?

MVC maintains a ModelState collection which holds the posted back data along with validation result. When you display the same view back with the posted back model, MVC will display the original value user enters on the browser with possible validation errors. For data integrity reasons, MVC ignores your direct change on the view model data when it binds the data using the Html helper method. So your model.Id = newId will NOT work.

The workaround is either use pure HTML control

<input type=’hidden’ value=’@Model.Id’ />

or remove the individual entry in the ModelState collection

ModelState.Remove(“Id”)

ModelState.Clear() works too. It will remove everything including the validation messages.

Advertisements
This entry was posted in MVC and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s