I\'m developing an ASP.NET MVC 5 web with C# and .NET Framework 4.5.1.
I have this form
in a cshtml
file:
@model MyProduct.
you can visit this article for complete source code with a video tutorial.
you have to create an action first, from where we can pass the list of object
[HttpGet]
public ActionResult Index()
{
List model = new List();
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
model = dc.Contacts.ToList();
}
return View(model);
}
then we need to create a view for that action
@model List
@{
ViewBag.Title = "Update multiple row at once Using MVC 4 and EF ";
}
@using (@Html.BeginForm("Index","Home", FormMethod.Post))
{
Contact Person
Contact No
Email ID
@for (int i = 0; i < Model.Count; i++)
{
@Html.HiddenFor(model => model[i].ContactID)
@Html.EditorFor(model => model[i].ContactPerson)
@Html.EditorFor(model => model[i].Contactno)
@Html.EditorFor(model => model[i].EmailID)
}
@ViewBag.Message
}
@section Scripts{
@Scripts.Render("~/bundles/jqueryval")
}
and then we have to write code for save the list of object to the database
[HttpPost]
public ActionResult Index(List list)
{
if (ModelState.IsValid)
{
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
foreach (var i in list)
{
var c = dc.Contacts.Where(a =>a.ContactID.Equals(i.ContactID)).FirstOrDefault();
if (c != null)
{
c.ContactPerson = i.ContactPerson;
c.Contactno = i.Contactno;
c.EmailID = i.EmailID;
}
}
dc.SaveChanges();
}
ViewBag.Message = "Successfully Updated.";
return View(list);
}
else
{
ViewBag.Message = "Failed ! Please try again.";
return View(list);
}
}