简体   繁体   中英

Binding Model to List nested model

I have model that has few simple properties and one nested

public class GridViewModel 
{
    public property1 {get;set;}
    ...
    public List<Grid> Grids { get; set; }
}

public class Grid
{
    public int GridID { get; set; }
    public string GridName { get; set; }
    public string Description { get; set; }
    ...
}

In my view I am looping through Model.Grids and list all the properties. When i POST the model back to controller it comes back null. I have followed the Haacked instructions on how to bind to a list http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/ Am I missing something? In my view I tried using HiddenFor, TextBoxFor but nothing is coming back

 @for (int k = 0; k < Model.Grids.Count(); k++ )
{
     @Html.HiddenFor(modelItem => Model.Grids[k].GridID)
     @Html.TextBoxFor(modelItem => Model.Grids[k].GridID)
     @Html.DisplayFor(modelItem => Model.Grids[k].GridName)
     @Html.DisplayFor(modelItem => Model.Grids[k].Description)
}

Html comes out like

<input id="Grids_1__GridID" name="Grids[1].GridID" type="hidden" value="230">
<input id="Grids_2__GridID" name="Grids[2].GridID" type="hidden" value="231"> 

There was a caveat that I forgot to mention, I was submitting the page through the ActionLink which was passing a different parameter. My Model was coming empty as I was not submitting my page but calling an action. I have updated the link to a submit button which posts whole model and it was working fine now.

//used before
@Html.ActionLink("Export Excel", "ExportToExcel", "Grid", new { GridID = "gridsid"}, new { id = "exportExcelLink" })

//switched to
<button type="submit" id="exportLink" name="exportBtn">[Export BTN]</button>

The default binder might be getting confused since you are posting back HiddenFor and TextBoxFor . I would simply try:

@for (var k = 0; k < Model.Grids.Count(); k++)
{
    @Html.HiddenFor(m => m.Grids[k].GridID)
}

Make sure it is zero-indexed and you should be good to go.

Also, notice I use m to index, not Model .

//define int variable
int i=0;

@foreach (var item in Model.Grids)
{
     @Html.HiddenFor(m=> m.Grids[i].GridID)
     @Html.TextBoxFor(m=> m.Grids[i].GridID)
     @Html.DisplayFor(m=> m.Grids[i].GridID)
     @Html.DisplayFor(m=> m.Grids[i].GridID)
i=i+1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM