这是我的代码:
模型
public class InformationsModel
{
public List<InformationModel> infos { get; set; }
public InformationsModel()
{
}
}
public class InformationModel
{
public InformationModel() {
}
public string Name { get; set; }
public string Value { get; set; }
public string Group { get; set; }
public string Type { get; set; }
public bool Avaiable { get; set; }
}
查看
@model InterfaceWeb.Models.InformationsModel
@using (Html.BeginForm("UpdateInformations", "Main", FormMethod.Post, new { @id = "frmInformations" }))
{
@Html.EditorFor(x => x.infos)
}
模板
@model InterfaceWeb.Models.Information.InformationModel
<div class="infoMain">
<div class="colunas">
@Html.TextBoxFor(x => x.Name, new { style = "width:250px;" })
</div>
<div class="colunas">
@Html.TextBoxFor(x => x.Value, new { style = "width:120px;" })
</div>
<div class="colunas">
@Html.TextBoxFor(x => x.Group, new { style = "width:120px;" })
</div>
<div class="colunas">
@Html.TextBoxFor(x => x.Type, new { style = "width:150px;" })
</div>
<div class="colunas">
@Html.CheckBoxFor(x => x.Avaiable, new { style = "width:10px; margin-left:20px;" })
</div>
</div>
Controller
[HttpPost]
public ActionResult UpdateInformations(InformationsModel infos)
{
}
当我到达 Controller 时,我的模型是空的,我不明白为什么。
我尝试更改模板、 View 、初始化列表之后、之前,但没有任何效果..
感谢您的帮助! =)
最佳答案
由于模型前缀的工作方式,您遇到了此问题。具体来说,问题就在这里:
[HttpPost]
public ActionResult UpdateInformations(InformationsModel infos)
{
}
如果您查看模板生成的 HTML,您会发现它的内容如下:
<input id="infos_0__Name" name="infos[0].Name" type="text" value="" />
在这种情况下,需要了解的重要一点是 infos
是与 InformationsModel.infos
属性值关联的前缀。通过在 Controller infos
中命名参数,您将摆脱模型绑定(bind)器。您只需重命名它即可获取值,如下所示:
[HttpPost]
public ActionResult UpdateInformations(InformationsModel model)
{
}
顺便说一句,我建议将 InformationModel
重命名为更合适的名称,例如 Person
、Employee
或任何您想要的名称造型。遵循您想要做的事情有点困难,只是因为类名称几乎相同,并且名称并没有真正传达它们的意图。
关于asp.net-mvc - MVC 4 列表模型向 Controller 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19073804/