Editing collections and disabling form persistance
Is there anyway to disable MVC "refilling" from form data for a particular request?
I'm developing an MVC sample that edits a "shopping cart", which contains of a simple list of items and their quantities. So far, so typical.
I'm using editor templates so that I can use EditorFor
on the list of items and MVC will generate the Items[x]
field prefix and provide me with basically free model binding on the post back.
Part of the sample is to remove items with a quantity of zero between posts. Unfortunately, since the HTML helper methods prioritise form values over model values, this is resulting in the number of items being reduced but the form data of the previous item that was posted at that position. Non-posted data for the row obviously remains correct.
NB. I realise that one would usually utilise the PRG pattern here, but since this is a sample there is no persista开发者_JS百科nce layer (I'm relying on form data + a static product repository implementation).
Edit: To be clear I'm not arguing against the PRG pattern, the sample is simply highlighting model binders and server side validation.
OK, it seems to be the problem I encountered: Strange behaviour in ASP.NET MVC: removing item from a list in a nested structure always removes the last item
The solution I found was to clear the ModelState and then populate with what you need.
Also PRG is possible, you have to store the model and modelstate temporarily in the session and on the GET, retrieve from session and remove. This is exactly what ASP NET MVC Contrib 2 was doing in ActionFilter PassParametersDuringRedirect
.
精彩评论