简体   繁体   中英

List of models in Model in MVC

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 Controller editing ModelOut:

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

In view I have sth like:

<% 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" />
<% } %>

It works all OK, but in post action I have empty ModelOut items. I can see in logs that data is sent correctly.

I have tried everything, nothing works.

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

MVC should loop through the list by itself.

Also, watch out how you specify your lambdas, it should be m => m rather than m => Model .

PS. I use MVC3...

The reason for your problem could be a naming mismatch...from what I remember the default model binder does not do its job properly because of this naming mismatch....this means you need to specify more info to the model binder to do its job better... try updating your View code to use the below code for each property...

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

The above view code will generate the following markup

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

I might have a syntactical problem above but I guess you can get it right with the help of Visual Studio

@Dai were right. MVC let me use items for model instance name when it is instance of List, but doesn't let me use it for ModelOut.

After renaming items to model it works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM