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 aforeach
loopA
foreach
generates duplicatename
attributes which have no relationship to your model (and duplicateid
attributes which is invalid html)