Reputation: 233
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">
Upvotes: 1
Views: 201
Reputation: 567
//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;
}
Upvotes: 0
Reputation: 233
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>
Upvotes: 1