List of models in the MVC model

I have two models:

class ModelIn{ public string FirstName { get; set; } public string LastName { get; set; } public string Address { get; set; } } class ModelOut{ public ModelOut(){ People = new List<ModelIn>();} public List<ModelIn> People { get; private set;} public string Country { get; set; } } 

And I have a Controller editing ModelOut:

 public ActionResult People() { ... return View(SomeModelOutInstanceWith3People); } [HttpPost] public ActionResult(ModelOut items) { ... } 

I think that

 <% using (Html.BeginForm()) { %> <%: Html.EditorFor(m => Model.Country) %> <% for(int i = 0; i < Model.People.Count; ++i){ %> <%: Html.EditorFor(m => Model.People[i].FirstName) %> <%: Html.EditorFor(m => Model.People[i].LastName) %> <%: Html.EditorFor(m => Model.People[i].Address) %> <% } %> <input type="submit" /> <% } %> 

Everything works fine, but in post action I have empty ModelOut elements. In the logs, I see that the data is being sent correctly.

I tried everything, nothing works.

+6
source share
3 answers

@ Dai were right. MVC allows me to use elements for the model instance name when it is a List instance, but does not allow me to use it for ModelOut.

After renaming items to model it works fine.

0
source

Have you tried just <%: Html.EditorFor(m => m.People) %> ?

MVC should automatically scroll through the list.

Also note how you specify your lambdas, this should be m => m , not m => Model .

PS. I am using MVC3 ...

+1
source

The cause of your problem may be a name mismatch ... from what I remember, the default mediator is not doing its job properly due to this name mismatch ... this means you need to provide more information for the mediator model so that to do your job better ... try updating your view code to use the code below for each property ...

 <%= Html.EditorFor(string.Format("People[{0}].FirstName", i), Model.People[i].FirstName) %> 

The above view code will create the following markup

 <input id="People_0__FirstName" name="People[0].FirstName" type="text" /> 

I may have the syntax problem above, but I think you can get it correctly using Visual Studio

0
source

Source: https://habr.com/ru/post/924653/


All Articles