我想将我的对象列表发布到我的控制器。
这是我的班级档案:
public class MyModel
{
public int Id {get; set;}
public List<ChildModel> ChildModelObject{ get; set; }
}
public class ChildModel
{
public int ChildId {get; set;}
public int sum {get; set;}
}
我的观看页面:
@model Demo.MyModel
@using (Html.BeginForm())
{
@{ int i = 0; }
@foreach (var item in Model.ChildModelObject) //first I am displaying value and then on submit i will post this value
{
<input type="hidden" name="@Html.Raw("ChildModelObject[" + i + "].ChildId")" value="@item.ChildId" /> //This is how i am taking value and it is working perfect and i am getting childid.
@Html.DisplayFor(modelItem => item.sum)
}
<input type="submit" value="Save"/>
}
控制器:
public ActionResult Index(MyModel model)//In this i want all childid when form is posted
{
}
所以现在当我点击提交按钮时,我想要 MyModel 对象中的所有 childid 。
有人可以告诉我任何更好的方法,然后我正在做什么?
答案 0 :(得分:1)
您应该为ChildModel
类创建编辑模板,如下所示:
@model Demo.ChildModel
@Html.HiddenFor(x => x.ChildId)
@Html.DisplayFor(x => x.sum)
将其放在Views/Shared/EditorTemplates
文件夹中(或在您的控制器EditorTemplates中)并将其命名为 ChildModel.cshtml
然后你可以像这样使用它:
@model Demo.MyModel
@using (Html.BeginForm())
{
@Html.EditorFor(x=>x.ChildModelObject)
<input type="submit" value="Save"/>
}
请注意,您不需要任何循环MVC自己生成正确的绑定