c#-指定Html.EditorFor的模板名称

我的PersonModel对象有多个编辑器模板:

>视图/人/EditorTemplates/PersonModel.cshtml
>视图/人/EditorTemplates/RestrictedPersonModel.cshtml
>视图/人/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生成与模型无关的重复名称属性(以及无效html的重复id属性)

上一篇:javascript-在IIS 8(Windows 8)上部署ASP.Net MVC应用程序时未呈现CSS和JS文件


下一篇:如何将ID从剃刀视图传递到ASP .Net MVC中控制器的操作方法?