指定带有List的Html.EditorFor的模板名称

时间:2015-11-26 12:10:00

标签: c# asp.net-mvc razor

我的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>不会传递到我的控制器中。

如何指定要使用的编辑器模板,并仍在控制器中接收数据?

1 个答案:

答案 0 :(得分:4)

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

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

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