HTML.CheckBox persisting state after POST - Refresh ModelState?

Posted by Kirschstein on Stack Overflow See other posts from Stack Overflow or by Kirschstein
Published on 2009-11-16T14:24:15Z Indexed on 2010/03/30 11:43 UTC
Read the original article Hit count: 534

Filed under:
|
|
|

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.

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about c#