I have been working with MVC for a little while now and always learning new things about it, yesterday I ran into something for the very first time, so wanted to share.

I’ve seen the pattern of using a single view for both creation/editing of a model, it’s not very uncommon. In this particular case, I was working with a controller that would save its bound model to the database and then assign it the unique id generated in the database. The idea being that if the id was null, this was a new model, and if the id existed, this was a model to be edited. After this id was assigned the controller returned the same view with the updated model. The only problem was that this newly edited unique id for the model was never making it back to the view. This was verified by a consistently empty @Html.HiddenFor input for the models id property.

So here is what I learned… when you are posting a model to a controller action, and then changing some values on that model, and returning the same view with that updated model…MVC will not use those model values. Instead, it will use the ModelState dictionary to populate our view.

There are a few ways around this (one of them being clearing model state in your controller), and thanks to Tejasvi’s explanation on this SOF thread, I now feel like I understand this more. Although, I am not entirely certain I understand why it works like this. That’s for another post :)