[英]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. 在我看来,我正在遍历Model.Grids并列出所有属性。 When i POST the model back to controller it comes back null.
当我将模型发布回控制器时,它返回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?
我遵循了Haacked关于如何绑定到列表的说明, http: //haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/我是否缺少某些内容? In my view I tried using HiddenFor, TextBoxFor but nothing is coming back
在我看来,我尝试使用HiddenFor,TextBoxFor,但是什么也没回来
@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 HTML出来像
<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. 我忘了要提一个警告,我是通过ActionLink提交页面的,该页面传递了一个不同的参数。 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
. 由于您要回发
HiddenFor
和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
. 另外,请注意,我使用
m
来索引,而不是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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.