MVC postback for users without JavaScript - Post 2
Posts in this series:
- Post 1
- Post 2
So far we have created a form which performs a postback to the server to add more input fields to the same page. We have encountered an issue with MVC seeming to cache partial views (or at least the values inside them).
Step 4
Step 4 attempts to fix the caching of the selected value field.
I spent hours looking for a way to stop MVC caching partial views, which is what I thought was happening. I tried disabling the output cache and loading the partial views via actions, neither of which helped. I finally found this answer on StackOverflow; the ModelState holds the old values when a view is reloaded via an HTTP POST even if you change the values of the model in the action.
By removing the specific value from the ModelState the value clears properly and the view displays as expected.
private ActionResult AddPostback(OrderViewModel model)
{
ModelState.Remove("SelectedMenuItem");
model.SelectedMenuItem = null;
return View("Order", model);
}
The form now works as expected, the "add another" button adds another input to the page by reloading the page, the submit button still submits the form to the server and redirects to the summary screen. Now we have the screen working for users without JavaScript however users get a "screen flicker" due to reloading the page when clicking "Add another".
See this image for an example of the screen flicker non-JavaScript users will see, this seems like an acceptable compromise, since there's no way to prevent the page having to reload for these users. However for people with JavaScript enabled it would be nice to offer a cleaner user experience.