Friday 26 December 2014

MVC 4 Razor: Delete multiple rows in WebGrid with CheckBox selection and with confirmation in ASP.NET using C#.NET

Hi friends,in this article I will explain about How to delete multiple rows in WebGrid with CheckBox selection and with confirmation in ASP.NET MVC4 Razor using C#.NET.
I already explained in the previous articles about MVC 4 Razor: How to Select / Deselect All Checkboxes inside a Webgrid in ASP.NET Application using C#.NETMVC 4 Razor: Frozen Rows and Columns Webgrid Using jQuery Like Excel Sheet and MVC 4 Razor: Bind jQuery DatePicker Calendar in MVC WebGrid Using ASP.NET MVC, C#.Net

For this  I created one USERS table and insert the values like as shown in the below figure.
USERS Table SQL Script
CREATE TABLE USERS (
  User_id int IDENTITY (1, 1),
  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 ('Manika''Female''XXXXXXXX')
INSERT INTO USERS (UserName, Gender, Address)
  VALUES ('SambhaShiva''Male''XXXXXXXX')

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 MvcDelete_MultipleRecords.Models;

namespace MvcDelete_MultipleRecords.Controllers
{
    public class UserController : Controller
    {

        public ActionResult Index()
        {
            List<USER> objUsers = new List<USER>();
            UserDBEntities db = new UserDBEntities();
            objUsers = db.USERS.ToList();
            if (objUsers.Count <= 0)
                ViewBag.mes = "No Records Found";
            return View(objUsers);
        }

        [HttpPost]
        public ActionResult Index(string[] DeleteIds)
        {
            List<USER> objUsers = new List<USER>();
            int[] id = null;
            if (DeleteIds != null)
            {
                id = new int[DeleteIds.Length];
                int j = 0;
                foreach (string i in DeleteIds)
                {
                    int.TryParse(i, out id[j++]);
                }
            }
            if (id != null && id.Length > 0)
            {
                List<USER> selectedIds = new List<USER>();
                using (UserDBEntities db = new UserDBEntities())
                {
                    selectedIds = db.USERS.Where(a => id.Contains(a.User_id)).ToList();
                    foreach (var i in selectedIds)
                    {
                        db.USERS.DeleteObject(i);
                    }
                    db.SaveChanges();
                    objUsers = db.USERS.ToList();
                }
                ViewBag.Success = "Selected Records are Deleted Successfully";
            }
            return View(objUsers);
        }
    }
}


View(Index.cshtml):
@model IEnumerable<MvcDelete_MultipleRecords.Models.USER>
<style type="text/css">
    .btn
    {
        background-color: #4682CB;
        font-family: Tahoma;
        color: White;
        padding:5px;
    }
    .webGrid
    {
        margin-left: 5px;
        border-collapse: collapse;
        width: 700px;
        font-family: Tahoma;
        font-size: small;
    }
    .grid-header
    {
        background-color: #4682CB;
        font-weight: bold;
        color: White !important;
    }
    .webGrid th a
    {
        color: White;
        text-decoration: none;
    }
    .webGrid th, .webGrid td
    {
        border: 1px solid black;
        padding: 5px;
    }
    .alt
    {
        background-color: #F4EFEF;
    }
    .webGrid th a:hover
    {
        text-decoration: underline;
    }
    .to-the-right
    {
        text-align: right;
    }
</style>

<script type = "text/javascript">
    function ConfirmDelete() {
            return confirm("Do you want to delete records.");
    }
</script>

@using (Html.BeginForm("Index", "User", FormMethod.Post))
{
    <h5 style="color: Green; font-family: Tahoma">@ViewBag.Success</h5>
    <h5 style="color: Red; font-family: Tahoma">@ViewBag.mes</h5>
    var grid = new WebGrid(source: Model, rowsPerPage: 10);
    @grid.GetHtml(
        tableStyle: "webGrid",
        htmlAttributes: new { id = "DeleteSelectedWebGrid" },
        headerStyle: "grid-header",
        rowStyle: "gridRow",
        alternatingRowStyle: "alt",
        mode: WebGridPagerModes.All,
        firstText: "<< First",
        previousText: " < Previous",
        nextText: "Next >",
        lastText: "Last >>",
        caption: "User Details",
        columns: grid.Columns(
            @*Here I am adding Checkbox Column for selecting multiple records*@
grid.Column(format: @<text><input type="checkbox" name="DeleteIds"  id="chk" value="@item.User_id" /></text>, header: "Select"),
        grid.Column("UserName", "User Name"),
        grid.Column("Gender", "Gender"),
        grid.Column("Address", "Address")
        )
    )
    <br />
    <input type="submit" value="Delete Selected" class="btn" onclick="javascript:return ConfirmDelete();"/><br />
}

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

When you select the records by selecting the checkboxes and click on Delete Selected button then its shows the confirmation message as shown in the below figure.



If you click on Ok button then selected records will be deleted as shown in the below figure. 

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

No comments:

Post a Comment

© 2012-2018 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.