So, I have a collection of User objects that should be available for bulk editing (edit many users at the same time). I save user login to the database using Entity Framework.
The collection that the controller method receives from the form is null. What for? Also, is it possible to use BindAttribute with collections, as 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"); }
c # asp.net-mvc entity-framework asp.net-mvc-5 model-binding
Andrew
source share