我无法绑定包含编辑方法对象列表的模型。这是Factory
的列表,其中包括另一个对象(FactoryHotline
)的列表。
当我从Controller传递数据到View时没有问题。但是当我尝试将数据从View发送回Controller时,某些模型的属性始终为null。
该模型是:
public class Factory
{
public Guid Id { get; set; }
public string Name { get; set; }
public List<FactoryHotline> FactoryHotlineList { get; set; }
}
public class FactoryHotline
{
public Guid Id { get; set; }
public Guid FactoryId { get; set; }
public string Caption { get; set; }
public string Hotline { get; set; }
}
这是视图:
@model List<WebDataLayer.Models.Factory>
<form action="/Factories/Edit" method="POST" enctype="multipart/form-data">
@Html.AntiForgeryToken()
<div class="form-horizontal">
<table id="factoriesTable">
<thead>
<tr>
<th>Name</th>
<th class="Hotline1" >Hotline 1</th>
<th class="Hotline2" >Hotline 2</th>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.Count; i++)
{
@Html.HiddenFor(model => model[i].Id)
<tr>
<td>@Model[i].Name</td>
@for (int h = 0; h < Model[i].FactoryHotlineList.Count; h++)
{
<td>
<div>
<b>Caption: </b>
@Html.EditorFor(model => model[i].FactoryHotlineList[h].Caption, new { htmlAttributes = new { @class = "form-control ShortInput", id = "captionInput", maxlength = "39" } })
</div>
<div>
<b>Hotline:</b>
@Html.EditorFor(model => model[i].FactoryHotlineList[h].Hotline, new { htmlAttributes = new { @class = "form-control ShortInput", id = "hotlineInput", maxlength = "15" } })
@Html.ValidationMessageFor(model => model[i].FactoryHotlineList[h].Hotline)
</div>
</td>
}
</tr>
}
</tbody>
</table>
</form>
在我的控制器中,编辑的方法是:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit (List<Factory> factories)
{
}
只有Id有价值,另一个(标题,热线)在List<Factory> factories
中始终为空
这就是我将数据从Controller传递到View的方式
// GET: Edit
public ActionResult Edit()
{
var factories = _factoryService.All().OrderBy(p => p.Name);
var list = factories.ToList();
return View("Edit", list);
}
我使用Entity Framework工作得很好。
那是因为你使用HiddenFor
将id保持为隐藏字段。要在回发中使用该值,它应该是input元素的一部分(input,select,checkbox,textarea等)或隐藏字段。
@Html.HiddenFor(model => model[i].Name)
在这种情况下,我建议使用viewmodel along with automapper。