i have model property of type list. use property show values on view. use foreach loop go through each item in list , displaying them using displayfor , textboxfor. part working fine; i've used textboxfor before , user entered text gets past model on submit. however, when using list, list null when form submitted. other properties in model updated , can access them correctly. preventing list binding , how can fix this?
modelinstrumentlistingdetail
public class modelinstrumentlistingdetail { public int instrumenttagid { get; set; } public string instrumenttagdescription { get; set; } public list<modelinstrumentlistingitem> items { get; set; } } modelinstrumentlistingitem
public class modelinstrumentlistingitem { public string field { get; set; } public string label { get; set; } } view
@model gpc.models.modelinstrumentlistingdetail @using (html.beginform("instrumentlistingadd", "home", formmethod.post, new { id = "instrumentlistingdetailform" })) { <table> <tr> <td> @html.textboxfor(m => m.instrumenttagdescription) </td> </tr> @foreach (gpc.models.modelinstrumentlistingitem item in model.items) { <tr> <td> @html.displayfor(m => item.label) </td> <td> @html.textboxfor(m => item.field) </td> </tr> } </table> <input id="submitinstrumentlistingadd" name="submitinstrumentlistingadd" value="add" type="submit" class="savebutton" /> } controller
[httppost] public actionresult instrumentlistingadd(modelinstrumentlistingdetail model, string submitinstrumentlistingadd) { ... } on submit, model posted controller has instrumentdescription value, items null. need figure out how fill items new values.
change loop so:
@for(int idx = 0;idx < model.items.count;idx++) { <tr> <td> @html.displayfor(_ => model.items[idx].label) </td> <td> @html.textboxfor(_ => model.items[idx].field) </td> </tr> } the reason works <input> elements generated so:
<input id="items_0_" name="items[0]" type="text" value="foo"> <input id="items_1_" name="items[1]" type="text" value="bar">
when post data, following in body:
items[0]:foo items[1]:bar the default asp.net mvc model binder pick these items request body , apply them viewmodel, in case modelinstrumentlistingdetail.items
Comments
Post a Comment