INTRODUCTION
In this post I am explain how to update multiple row at once in MVC. Just follow the steps and get result within 15 minute.PREREQUISITE
I used followings:- .Net framework 4.0
- Entity Framework
- Jquery
- Sql Server 2008
STEPS
Just follow the steps and get result easily.STEP-1: CREATE NEW PROJECT
First we need to create a project.Go to Menu File > New > Project > select asp.net mvc4 web application > Entry Application Name > Click OK.
STEP-2: ADD A DATABASE.
Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

STEP-3: ADD ENTITY DATA MODEL.
Go to Solution Explorer > Right Click on Project Name from Solution Explorer folder > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.

Here we need to modify contact.cs file

namespace UpdateMultiRecord
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class Contact
{
[Required]
public int ContactID { get; set; }
[Required]
public string ContactPerson { get; set; }
[Required]
public string Contactno { get; set; }
public string EmailID { get; set; }
}
}
STEP-4: IMPLEMENT ACTION FOR GET & POST METHOD.
Here I am using Home controller index action.Get Action
[HttpGet]Post Actionpublic ActionResult Index(){List<Contact> model = new List<Contact>();using (MyDatabaseEntities dc = new MyDatabaseEntities()){model = dc.Contacts.ToList();}return View(model);}
[HttpPost]public ActionResult Index(List<Contact> 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);}}
STEP-5: CREATE VIEW FOR UPDATE MULTIPLE ROW.
Our View Index.cshtml
@model List<UpdateMultiRecord.Contact>
@{
ViewBag.Title = "Update multiple row at once Using MVC 4 and EF ";
}
@using (@Html.BeginForm("Index","Home", FormMethod.Post))
{
<table>
<tr>
<th></th>
<th>Contact Person</th>
<th>Contact No</th>
<th>Email ID</th>
</tr>
@for (int i = 0; i < Model.Count; i++)
{
<tr>
<td> @Html.HiddenFor(model => model[i].ContactID)</td>
<td>@Html.EditorFor(model => model[i].ContactPerson)</td>
<td>@Html.EditorFor(model => model[i].Contactno)</td>
<td>@Html.EditorFor(model => model[i].EmailID)</td>
</tr>
}
</table>
<p><input type="submit" value="Save" /></p>
<p style="color:green; font-size:12px;">
@ViewBag.Message
</p>
}
@section Scripts
{@Scripts.Render("~/bundles/jqueryval")}Here @Scripts.Render("~/bundles/jqueryval") this will enable client side validation.
STEP-6: RUN APPLICATION.
Edit Contact Details and Click Save button.
0 comments:
Post a Comment