views:

317

answers:

2

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.

A: 

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

Daniel Elliott
Yeah, I see that - but why is this state remembered over different requests?
Kirschstein
A: 

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.

dove