我的PersonModel
对象有多个编辑器模板:
Views/Person/EditorTemplates/PersonModel.cshtml
Views/Person/EditorTemplates/RestrictedPersonModel.cshtml
Views/Person/EditorTemplates/NoImagePersonModel.cshtml
作为测试,这些编辑器模板是相同的:
@model MyApp.Models.PersonModel
@Html.TextBoxFor(model => model.Name)
使用以下视图时:
@model List<MyApp.Models.PersonModel>
@{
ViewBag.Title = "Basket";
}
<h1>All People</h1>
@if (Model.Count() > 0)
{
<div>
This is a list of all the people:
</div>
using (Html.BeginForm("SendID", "Person", FormMethod.Post))
{
<div>
@Html.EditorFor(model => model)
</div>
<div class="col-md-12">
<button type="submit">
Email IDs
</button>
</div>
}
}
else
{
<div>
There are no people.
</div>
}
使用Views/Person/EditorTemplates/PersonModel.cshtml
编辑器模板,List<PersonModel>
根据需要传递给控制器。
但是,当我指定模板时:
@Html.EditorFor(model => model, "RestrictedPersonModel")
我收到以下错误:
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[MyApp.Models.PersonModel]', but this dictionary requires a model item of type 'PrintRoom.Models.PersonModel'.
更换时
@Html.EditorFor(model => model, "RestrictedPersonModel")
与
@foreach (PersonModel p in Model)
{
@Html.EditorFor(model => p, "RestrictedPersonModel")
}
然后List<PersonModel>
不会传递到我的控制器中。
如何指定要使用的编辑器模板,并仍在控制器中接收数据?
答案 0 :(得分:4)
您需要使用for
循环而不是foreach
循环
for(int i = 0; i < Model.Count; i++)
{
@Html.EditorFor(m => m[i], "RestrictedPersonModel")
}
foreach
生成与您的模型无关的重复name
属性(以及无效的html重复的id
属性)