how to request collection of fields in mvc
i have the following foreach. Inside you'll see a text box for quantity. At the bottom of the page there is submit button. What is the best practise for saving a collection of fields like this in asp.net MVC. ie how would i get the values 开发者_开发问答in my controller
<% foreach(var item in Model.Results) { %>
<tr class="RowStyle">
<td><input name="quantity" value="<%= item.Quantity %>" class"input-30" /></td>
</tr>
<% } %>
See Phil Haack's blog post on model binding to a list.
The basic idea is that you need to tell the model binder about each element you are passing back so that it can build up the collection of items with the proper data. Since the post will send back comma-separated lists of data for each name, you need to build the name with indices so that all of the properties of each item will be "grouped" together (I assume that each item has more properties than just quantity). It might look something like:
<% int index = 0;
foreach(var item in Model.Results)
{ %>
<tr class="RowStyle">
<td>
<%= Html.Hidden( "items.Index", index ) %>
<%= Html.TextBox( "items[" + index + "].Quantity", item.Quantity, null ) %>
</td>
<td>
... additional properties
</td>
</tr>
<% ++index;
} %>
精彩评论