I am using FormCollection for this purpose.
Watch this example on YouTube:
I will be editing FirstName and LastName in table above.(Please ignore DepartmentID column, I am not going to use it in this tutorial) For that purpose I will create EF connection to the database (step by step examples in other MVC tutorials or in the video above) and will modify my View
@model IEnumerable<TestMultiUpdateWithMVC.Models.User>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm()){
<table>
@Html.ValidationSummary(true)
<tr>
<th>
@Html.DisplayNameFor(model => model.FirstName)
</th>
<th>
@Html.DisplayNameFor(model => model.LastName)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.HiddenFor(modelItem => item.UserId)
</td>
<td>
@Html.EditorFor(modelItem => item.FirstName)
@Html.ValidationMessageFor(model => item.FirstName)
</td>
<td>
@Html.EditorFor(modelItem => item.LastName)
@Html.ValidationMessageFor(model => item.LastName)
</td>
</tr>
}
</table>
<input type="submit" value="save" />
}
So it produces page that presents all users with Save button
Now I will add the following code to the controller
[HttpPost]
public ActionResult Index(FormCollection c)
{
int i = 0;
if (ModelState.IsValid)
{
var UserIDArray = c.GetValues("item.UserId");
var UserFirstNameArray = c.GetValues("item.FirstName");
var UserLastNameArray = c.GetValues("item.LastName");
for (i = 0; i < UserIDArray.Count(); i++)
{
User usr = db.Users.Find(Convert.ToInt32(UserIDArray[i]));
usr.FirstName = UserFirstNameArray[i];
usr.LastName = UserLastNameArray[i];
db.Entry(usr).State = EntityState.Modified;
}
db.SaveChanges();
}
return View(db.Users.ToList());
}
That's it! - Since I know that all arrays will have the same size, I can load all values to my arrays, then update my user(s).