I have a standard form in mvc4 operation. I use jQuery.post to perform postback to action on server:
[HttpPost]
public ActionResult ContactUpdate(ContactClass model)
{
var originalContact = contactService.Get(model.Id);
if (ModelState.IsValid && TryUpdateModel(originalContact))
{
contactService.Update(originalContact);
}
var updatedContact = contactService.Get(model.Id);
return PartialView("ContactView", updatedContact );
}
This works as expected, code is here only for illustration, as my issue occurs later in request. My contact service does not have update implemented (yet), so updatedContact is actually the same one as original (when you perform update all changes are ignored and old object is returned). So when I change i.e. PostCode in webpage from 555 to 666, updatedContact.PostCode is 555. I checked its value in debugger and also in view cshtml file where @Html.EditorFor(m=>m.PostCode) is called, and everywhere it has old value (not updated). The problem is that returned html (catched from net in firebug and chrome dev tools) has:
<input class="text-box" id="PostCode" name="PostCode" type="text" value="666">
This behavior is same for all properties, and as far as I know, there is no output caching (and even if it were, it is a POST request so cache should be bypassed). When I do refresh of the page, I get “old” values.
At first, I thought it is my ajaxSuccess function which does $("#myform").replaceWith(returnedText), but after double-checking response content I’m positive that problem is in returned html. How is this possible?
This bug now creates illusion that my update is working, and if it were working, I would probably not even know about it. This is potentially dangerous behavior because some properties can have value different from the one posted to controller, and user will not be able to see it after update, so I may have to refresh the whole page to workaround.
All the
Html.helpers are prefers theModelStatevalues over the actual model values.If you wan’t to return an updated model from a “postback” action you need to clear the
ModelStatefirst:This article is a good explanation of this feature of the mvc framework.