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
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.Clear() works too. It will remove everything including the validation messages.