List count empty when passing from view to model in ASP.Net MVC

走远了吗. 提交于 2019-12-11 11:53:29

问题


Before I begin, I have looked at this question:

asp.net mvc model binding fails for <List> items in editor template

I have a model which looks as so:

public class PartnerListModel
{
    public List<PartnersModel> Partners { get; set; }

    public PartnerListModel()
    {
        Partners = new List<PartnersModel>();
    }
}

And then my PartnersModel looks as such:

public class PartnersModel
{
    public int ID { get; set; }
    public string Name { get; set; }
    public bool IsActive { get; set; }
}

I'm passing the PartnersListModel to the view, which looks like this:

using (Html.BeginForm("Update", "Partners", FormMethod.Post))
            {
                @Html.EditorFor(m => m.Partners)
                <input type="submit" value="Submit Changes"/>
            }

And finally, my editor template looks like this:

@model AdminWebsite.Models.Partners.PartnersModel
<div>
    <span>
        @Html.DisplayFor(m => m.Name)
    </span>
    <span>
        @Html.EditorFor(m => m.IsActive)
    </span>
    @Html.HiddenFor(m => m.ID)
    @Html.HiddenFor(m => m.Name)
</div>

My controller's action is as so, and the code does actually manage to hit this action:

public ActionResult Update(PartnerListModel partners)

Why is it that my List inside the model has a count of 0? I can't find any reason why my example differs from an accepted answer on Stack Overflow. Is there anything that I am missing that would explain why my data values passed back are not being added to the list?

Using Chrome's developer tools I've been able to confirm that I have a list which looks similar to the following:

  • Partners[0].IsActive = true
  • Partners[0].IsActive = false
  • Partners[0].Name = "Hi"
  • Partners[0].ID = 1
  • Partners[1].IsActive = false etc.

Any ideas? Thanks in advance.


回答1:


You're passing a List<PartnersModel> to the action method, but the action-method expects a PartnerListModel.

You should change the Action-method like this:

public ActionResult Update(List<PartnersModel> partners)

The reason for this is that the default ModelBinder doesn't actually nest the graph. If you would want access to both items, you would need to do include both parameters:

public ActionResult Update(PartnerListModel partnerlistmodel, List<PartnersModel> partners){

}

If you want a nested model, you'd have to implement your own modelbinder.

The following question has a similar problem: Binding an editable list of children



来源:https://stackoverflow.com/questions/16553287/list-count-empty-when-passing-from-view-to-model-in-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!