ASP.NET - Batch submit

  • Model
using System.Collections.Generic;
 
namespace Northwind.Mvc.Models
{
    public class EditCustomersModel
    {
        public List<Customers> Customers { get; set; }
 
        public EditCustomersModel()
        {
            Customers = new List<Mvc.Customers>();
        }
    }
}
  • Controller
[HttpGet]
public ActionResult EditCustomers()
{
    using (var db = new NorthwindDBEntities()) {
        var list = db.Customers;
        return View("EditCustomers", new EditCustomersModel() { Customers = list.ToList() });
    }
}
 
[HttpPost]
public ActionResult SaveCustomers(EditCustomersModel model)
{
    using (var db = new NorthwindDBEntities()) {
        foreach (var c in model.Customers) {
            var customer = db.Customers.SingleOrDefault(x => x.CustomerID == c.CustomerID);
            if (customer != null) {
                customer.ContactName = c.ContactName;
                customer.ContactTitle = c.ContactTitle;
                customer.CompanyName = c.CompanyName;
                customer.Country = c.Country;
                customer.City = c.City;
                customer.Phone = c.Phone;
            }
        }
        db.SaveChanges();
        return RedirectToAction("EditCustomers");
    }
}
  • View
@using Northwind.Mvc.Models;
@model EditCustomersModel
 
@{
    ViewBag.Title = "Edit Customers";
}
 
<h2>Edit Customers</h2>
<hr />
 
<form action="@Url.Action("SaveCustomers", "Home")" method="post">
    <table>
        <thead>
            <tr>
                <th></th>
                <th>Contact Name</th>
                <th>Contact Title</th>
                <th>Company Name</th>
                <th>Country</th>
                <th>City</th>
                <th>Phone</th>
            </tr>
        </thead>
        <tbody>
            @{
                for (int i = 0; i < Model.Customers.Count; i++) {
                    <tr>
                        <td>@Html.HiddenFor(m => Model.Customers[i].CustomerID)</td>
                        <td>@Html.EditorFor(m => Model.Customers[i].ContactName)</td>
                        <td>@Html.EditorFor(m => Model.Customers[i].ContactTitle)</td>
                        <td>@Html.EditorFor(m => Model.Customers[i].CompanyName)</td>
                        <td>@Html.EditorFor(m => Model.Customers[i].Country)</td>
                        <td>@Html.EditorFor(m => Model.Customers[i].City)</td>
                        <td>@Html.EditorFor(m => Model.Customers[i].Phone)</td>
                    </tr>
                }
            }
        </tbody>
    </table>
 
    <hr />
    <input type="submit" value="Submit" class="form-control" />
</form>