我正在尝试使用FormMethod.Post从视图向控制器传递带有IEnumerable的模型,但是当在控制器中调用post方法时,模型IEnumerable为null。我一直在研究不同的解决方案但没有任何工作。我知道使用angular或javascript会更容易,但在这种情况下我不能。所以我的问题是有一种自定义绑定IEnumerable的方法吗?
index.cshtml - >图
@model MyProject.Web.ViewModels.PeopleData;
@using (Html.BeginForm("SaveList", "People", FormMethod.Post))
{
@Html.LabelBoxFor(x => x.Country);
//??? Cant find any binding tools that will work
@for(int i = 0 ; i < Model.Names; i++)
{
@Html.CheckBoxFor(x => x.Names[i].Valid)
@Html.LabelFor(x => x.Names[i].Name)
}
<input type='submit' value='save'>
}
PeopleController.cs - &gt;控制器
public ActionResult SaveList (PeopleData model)
{
// model.Names = null
// model.Country != null
DoSomething();
}
PeopleData.cs - &gt;模型
public PeopleData()
{
public string Country {get; set;}
public IEnumerable<FullName> Names {get; set;}
}
FullName.cs
public FullName()
{
public bool Valid {get; set;}
public string Name {get; set;}
}
基本上我希望视图列出带有复选框的所有名称,如果用户单击复选框,则将bool设置为true,如果取消选中,则将Valid设置为false。然后,当他们点击提交时,我想将更新的模型发送到控制器
答案 0 :(得分:0)
@model MyProject.Web.ViewModels.PeopleData;
@using (Html.BeginForm("SaveList", "People", FormMethod.Post))
{
@Html.LabelBoxFor(x => x.Country)
@Html.EditorFor(x => x.Names)
<input type='submit' value='save'>
}
这解决了它并且EditorFor的优点在于它为您创建了一个复选框列表,并会自动为您更新bool值(在这种情况下有效)。
答案 1 :(得分:0)
// This is Model
public PeopleData()
{
public string Country {get; set;}
public List<FullName> Names {get; set;} // use list here.
}
// This is View
@model MyProject.Web.ViewModels.PeopleData;
@using (Html.BeginForm("SaveList", "People", FormMethod.Post))
{
@Html.LabelBoxFor(x => x.Country);
@for(int i = 0 ; i < Model.Names.Count(); i++)
{
@Html.CheckBoxFor(x => x.Names[i].Valid)
@Html.LabelFor(x => x.Names[i].Name)
@Html.HiddenFor(x => x.Names[i].Name)
}
<input type='submit' value='save'>
}
// This is Post Action Method
[HttpPost]
public ActionResult SaveList (PeopleData model)
{
// here loop through model.Names to get the names and checkbox values..
}