gpt4 book ai didi

c# - 为采用 List 的 Html.EditorFor 指定模板名称

转载 作者:行者123 更新时间:2023-11-30 15:23:48 27 4
gpt4 key购买 nike

我的 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)

使用以下 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>
}

Views/Person/EditorTemplates/PersonModel.cshtml使用编辑器模板,List<PersonModel>根据需要传递给 Controller ​​。

但是,当我指定模板时:

@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>没有传递到我的 Controller 中。

如何指定要使用的编辑器模板,并且仍然在我的 Controller 中接收数据?

最佳答案

您需要使用for 循环而不是foreach 循环

for(int i = 0; i < Model.Count; i++)
{
@Html.EditorFor(m => m[i], "RestrictedPersonModel")
}

foreach 生成与您的模型无关的重复 name 属性(以及无效 html 的重复 id 属性)

关于c# - 为采用 List 的 Html.EditorFor 指定模板名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33938364/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com