ASP.NET MVC5: Want to update several items in Collection with model binding

女生的网名这么多〃 提交于 2019-12-04 22:05:34

问题


So I have a Collection of User objects, which should be mass-editable (edit many users at the same time). I'm saving the user input to the database using Entity Framework.

The collection the controller method gets from the form is null. Why? Also, is the BindAttribute possible to use with collections like in my code?

View:

@model IEnumerable<Domain.User>
@using (Html.BeginForm("UpdateUsers", "Users"))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    foreach (var item in Model)
    {
        @Html.HiddenFor(modelItem => item.Id)
        @Html.EditorFor(modelItem => item.FirstName)
        @Html.ValidationMessageFor(model => item.FirstName)
        @Html.EditorFor(modelItem => item.LastName)
        @Html.ValidationMessageFor(model => item.LastName)
        @Html.EditorFor(modelItem => item.Birth)
        @Html.ValidationMessageFor(model => item.Birth)
    }

    <input type="submit" value="Update user data"/>
}

Controller:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UpdateUsers([Bind(Include = "Id,FirstName,LastName,Birth")] IEnumerable<User> users)
{
    if (ModelState.IsValid)
    {
        foreach (User u in users)
        {
            db.Entry(u).State = EntityState.Modified;
        }
        db.SaveChanges();
    }

    return RedirectToAction("EditUsers");
}

回答1:


You need to index your collection with a for rather than a foreach in order for the ModelBinder to pick it up:

for (var i = 0 ; i < Model.Count(); i++)
    {
        @Html.HiddenFor(modelItem => modelItem[i].Id)
        @Html.EditorFor(modelItem => modelItem[i].FirstName)
        @Html.ValidationMessageFor(modelItem => modelItem[i].FirstName)
        @Html.EditorFor(modelItem => modelItem[i].LastName)
        @Html.ValidationMessageFor(modelItem => modelItem[i].LastName)
        @Html.EditorFor(modelItem => modelItem[i].Birth)
        @Html.ValidationMessageFor(modelItem => modelItem[i].Birth)
    }


来源:https://stackoverflow.com/questions/25915249/asp-net-mvc5-want-to-update-several-items-in-collection-with-model-binding

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