[英]Specify template name for Html.EditorFor which takes List
我的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>
不會傳遞到我的控制器中。
如何指定要使用的編輯器模板,仍然可以在控制器中接收數據?
您需要使用for
循環而不是foreach
循環
for(int i = 0; i < Model.Count; i++)
{
@Html.EditorFor(m => m[i], "RestrictedPersonModel")
}
foreach
生成與您的模型沒有關系的重復name
屬性(以及無效的html重復的id
屬性)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.