Monday, 29 December 2014

How to Update multiple rows at once Using MVC 4 Razor and Entity Framework

Hi friends, in this article I will explain about How to Update multiple rows at once Using MVC 4 Razor and Entity Framework.
For this I created one USERS table and insert the values like as shown in the below figure.

SQL Script for USERS Table 
CREATE TABLE USERS (
  User_id int IDENTITY (1, 1) PRIMARY KEY,
  UserName varchar(100),
  Gender varchar(10),
  Address varchar(200)
)

INSERT INTO USERS (UserName, Gender, Address)
  VALUES ('Kishore', 'Male', 'XXXXXXXX')
INSERT INTO USERS (UserName, Gender, Address)
  VALUES ('Satyam', 'Male', 'XXXXXXXX')
INSERT INTO USERS (UserName, Gender, Address)
  VALUES ('Rithvika', 'Female', 'XXXXXXXX')
INSERT INTO USERS (UserName, Gender, Address)
  VALUES ('SaiR', 'Female', 'XXXXXXXX')
INSERT INTO USERS (UserName, Gender, Address)
  VALUES ('SambhaShiva', 'Male', 'XXXXXXXX')

First we need to create a project.
Go to Menu File > New > Project > select ASP.NET MVC 4 web application > Entry Application Name > Click OK.
Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.NET Entity Data Model under data > Enter model name > Add.

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.



Controller(UserController.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcUpdateMultipleRows.Models;

namespace MvcUpdateMultipleRows.Controllers
{
    public class UserController : Controller
    {
        public ActionResult Index()
        {
            List<USER> userModel = new List<USER>();
            MvcDBEntities db = new MvcDBEntities();
            userModel = db.USERS.ToList();             
            return View(userModel);
        }
        [HttpPost]
        public ActionResult Index(List<USER> userList)
        {
            if (ModelState.IsValid)
            {
                using (MvcDBEntities db = new MvcDBEntities())
                {
                    foreach (var i in userList)
                    {
                        var userRows = db.USERS.Where(a => a.User_id.Equals(i.User_id)).FirstOrDefault();

                        if (userRows != null)
                        {
                            userRows.UserName = i.UserName;
                            userRows.Gender = i.Gender;
                            userRows.Address = i.Address;
                        }
                    }
                    db.SaveChanges();
                }

                ViewBag.Message = "Records have been Updated Successfully.";

                return View(userList);
            }
            else
            {
                ViewBag.Message = "Failed ! Please try again.";
                return View(userList);
            }
        }
    }
}

View(Index.cshtml):
@model List<MvcUpdateMultipleRows.Models.USER>
@{
    ViewBag.Title = "How to Update multiple rows at once Using MVC 4 Razor and Entity Framework";
}
<script type="text/javascript">
    function ConfirmUpdate() {
        return confirm("Do you want to Update the records.");
    }
</script>
@using (@Html.BeginForm("Index""User"FormMethod.Post))
{
    <table>
        <tr>
            <th>
            </th>
            <th>
                User Name
            </th>
            <th>
                Gender
            </th>
            <th>
                Address
            </th>
        </tr>
        @for (int i = 0; i < Model.Count; i++)
        {
            <tr>
                <td>@Html.HiddenFor(model => model[i].User_id)
                </td>
                <td>@Html.EditorFor(model => model[i].UserName)
                </td>
                <td>@Html.EditorFor(model => model[i].Gender)
                </td>
                <td>@Html.EditorFor(model => model[i].Address)
                </td>
            </tr>
        }
    </table>
    <p>
        <input type="submit" value="Update" onclick="javascript:return ConfirmUpdate();" /></p>
    <p style="color: green; font-size: 12px;">
        @ViewBag.Message
    </p>
}

The output of the above code as shown in the below figure.

When you update the rows and click on Update button then it will show the confirm message as "Do you want to Update the Records".If you click on "Yes" then record(s) will updated.
After updating the records it will show Records has been Updated Successfully.


You can download the code by clicking on the below Download button.

"If you like my blog or articles, you can appreciate by leaving your comments or Liking my Facebook page Aspdotnet-kishore, following on Google+ Aspdotnet-Kishore, Twitter on AspdotnetKishore, Linked in Aspdotnet-Kishore, stumbling my posts on stumble upon and subscribing on RSSfeed Aspdotnet-Kishore for free updates directly to your Email inbox . Watch my blog for more articles."

1 comment:

© 2012-2014 Aspdotnet-Kishore.blogspot.com. All Rights Reserved.
The content is copyrighted to Kishore and may not be reproduced on other websites without permission from the owner.