Monday, 22 June 2015

How to update multiple row at once Using MVC 4 and EF (Entity framework).

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.
Add Database
Open Database and add a table for update operation. Here I am creating a table called Contacts.

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.
Add Entity Model
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next > Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.
GenerateFromDatabase
After Creating Data model, we have to modify our generated entity(table) for Apply validation for required fields.
Here we need to modify contact.cs file
Contact.CS
Open file and modify as for enable validation.

namespace UpdateMultiRecord
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
   
    public partial class Contact
    {
        [Required]
        public int ContactID { getset; }
        [Required]
        public string ContactPerson { getset; }
        [Required]
        public string Contactno { getset; }
        public string EmailID { getset; }
    }
}

STEP-4: IMPLEMENT ACTION FOR GET & POST METHOD.

Here I am using Home controller index action.
Get Action 
       [HttpGet]
        public ActionResult Index()
        {
            List<Contact> model = new List<Contact>();
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                model = dc.Contacts.ToList();
            }
            return View(model);
        }
Post Action
       [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:greenfont-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.
Browser
Show message Successfully Updated.

YAHOO WE HAVE DONE...

0 comments: