C# – Specify template name for Html.EditorFor which takes List

asp.net-mvccrazor

I have multiple editor templates for my PersonModel object:

  • Views/Person/EditorTemplates/PersonModel.cshtml
  • Views/Person/EditorTemplates/RestrictedPersonModel.cshtml
  • Views/Person/EditorTemplates/NoImagePersonModel.cshtml

As a test, these editor templates are identical:

@model MyApp.Models.PersonModel

@Html.TextBoxFor(model => model.Name)

When using the following 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>
}

the Views/Person/EditorTemplates/PersonModel.cshtml editor template is used, and the List<PersonModel> is passed through to the controller as required.

However, when I specify the template:

@Html.EditorFor(model => model, "RestrictedPersonModel")

I recieve the following error:

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'.

When replacing

@Html.EditorFor(model => model, "RestrictedPersonModel")

with

@foreach (PersonModel p in Model)
{
    @Html.EditorFor(model => p, "RestrictedPersonModel")
}

then the List<PersonModel> is not passed through into my controller.

How can I specify the editor template to be used, and still receive the data in my controller?

Best Answer

You need to use a for loop rather than a foreach loop

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

A foreach generates duplicate name attributes which have no relationship to your model (and duplicate id attributes which is invalid html)

Related Topic