Lov*_*own 7 c# asp.net-mvc razor
我的PersonModel对象有多个编辑器模板:
Views/Person/EditorTemplates/PersonModel.cshtmlViews/Person/EditorTemplates/RestrictedPersonModel.cshtmlViews/Person/EditorTemplates/NoImagePersonModel.cshtml作为测试,这些编辑器模板是相同的:
@model MyApp.Models.PersonModel
@Html.TextBoxFor(model => model.Name)
Run Code Online (Sandbox Code Playgroud)
使用以下视图时:
@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>
}
Run Code Online (Sandbox Code Playgroud)
使用Views/Person/EditorTemplates/PersonModel.cshtml编辑器模板,并根据List<PersonModel>需要传递给控制器。
但是,当我指定模板时:
@Html.EditorFor(model => model, "RestrictedPersonModel")
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
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'.
Run Code Online (Sandbox Code Playgroud)
更换时
@Html.EditorFor(model => model, "RestrictedPersonModel")
Run Code Online (Sandbox Code Playgroud)
和
@foreach (PersonModel p in Model)
{
@Html.EditorFor(model => p, "RestrictedPersonModel")
}
Run Code Online (Sandbox Code Playgroud)
然后List<PersonModel>它不会传递到我的控制器中。
如何指定要使用的编辑器模板,并且仍然在我的控制器中接收数据?
小智 6
您需要使用for循环而不是foreach循环
for(int i = 0; i < Model.Count; i++)
{
@Html.EditorFor(m => m[i], "RestrictedPersonModel")
}
Run Code Online (Sandbox Code Playgroud)
Aforeach生成name与您的模型无关的重复id属性(以及无效 html 的重复属性)
| 归档时间: |
|
| 查看次数: |
5573 次 |
| 最近记录: |