HTML.CheckBox persisting state after POST - Refresh ModelState?
I have a form that's made up of many items (think order items on an amazon order). Each row has a 开发者_运维知识库checkbox associated with them so the user can select many items and click 'remove'.
The form is built up a bit like this;
<% for (int i = 0; i < Model.OrderItems.Count; i++) { %>
<tr>
<td><%= Html.Hidden(String.Format("OrderItems[{0}].Id", i), Model.OrderItems[i].Id)%>
<%= Html.CheckBox(String.Format("OrderItems[{0}].Checked", i), Model.OrderItems[i].Checked)%></td>
<td><%= Html.TextBox(String.Format("OrderItems[{0}].Name", i), Model.OrderItems[i].Name)%></td>
<td><%= Html.TextBox(String.Format("OrderItems[{0}].Cost", i), Model.OrderItems[i].Cost)%></td>
<td><%= Html.TextBox(String.Format("OrderItems[{0}].Quantity", i), Model.OrderItems[i].Quantity)%></td>
</tr>
<% } %>
The model binder does its magic just fine and the list is correctly populated. However, after I process the request in the action (e.g. remove the appropriate items) and return a new view containing fewer items, the state of the form is 'semi' persisted. Some check boxes remain checked, even though in the edit model all the bools are set to false.
I don't have this problem if I return a RedirectToActionResult
, but using that as a solution seems a bit of a hacky work around.
I think I need to flush/refresh the ModelState, or something similiar, but I'm unsure of the terms to search for to find out how.
If you check the rendered HTML I think you will find a hidden input of same name as your checkbox; this is the way the HTML.Checkbox
works. It does lead to an array of values being submitted.
This could be the cause of your problem.
Kindness,
Dan
I would like to see your controller code but think you're viewModel is being filled by fact of convention.
In your Index action I'm guessing you create a new viewModel. Try name this differently, call the instance indexViewModel say and it will not automagically gather the previous viewModel data.
Your hunch is probably correct, you likely need to call
ModelState.Remove("OrderItems[{0}].Checked");
btw using a Redirect normally isn't considered a hack, it's actually fairly a good practice called Post Redirect Get (PRG).
精彩评论