[英]Specify template name for Html.EditorFor which takes List
I have multiple editor templates for my PersonModel
object: 我的
PersonModel
对象有多个编辑器模板:
Views/Person/EditorTemplates/PersonModel.cshtml
Views/Person/EditorTemplates/RestrictedPersonModel.cshtml
Views/Person/EditorTemplates/NoImagePersonModel.cshtml
As a test, these editor templates are identical: 作为测试,这些编辑器模板是相同的:
@model MyApp.Models.PersonModel
@Html.TextBoxFor(model => model.Name)
When using the following view: 使用以下视图时:
@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>
}
the Views/Person/EditorTemplates/PersonModel.cshtml
editor template is used, and the List<PersonModel>
is passed through to the controller as required. 使用
Views/Person/EditorTemplates/PersonModel.cshtml
编辑器模板,并根据需要将List<PersonModel>
传递给控制器。
However, when I specify the template: 但是,当我指定模板时:
@Html.EditorFor(model => model, "RestrictedPersonModel")
I recieve the following error: 我收到以下错误:
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'.
When replacing 更换时
@Html.EditorFor(model => model, "RestrictedPersonModel")
with 同
@foreach (PersonModel p in Model)
{
@Html.EditorFor(model => p, "RestrictedPersonModel")
}
then the List<PersonModel>
is not passed through into my controller. 那么
List<PersonModel>
不会传递到我的控制器中。
How can I specify the editor template to be used, and still receive the data in my controller? 如何指定要使用的编辑器模板,仍然可以在控制器中接收数据?
You need to use a for
loop rather than a foreach
loop 您需要使用
for
循环而不是foreach
循环
for(int i = 0; i < Model.Count; i++)
{
@Html.EditorFor(m => m[i], "RestrictedPersonModel")
}
A foreach
generates duplicate name
attributes which have no relationship to your model (and duplicate id
attributes which is invalid html) foreach
生成与您的模型没有关系的重复name
属性(以及无效的html重复的id
属性)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.