Sunday, 15 September 2013

MVC Example For Delete Multiple Record in Gridview based on CheckBox Selection in MVC4






Description:-

            In this Example we explain that How to Delete Multiple Record at a time in Gridview in MVC. Here we Define Header Checkbox through which you can select All checkbox just in ane click and when you click on the Delete button ther all Selected Record are Deleted Successfully.

Generally in Simple Grid View that is very easy to Delete Multiple Record but in MVC that is a Difficult task here we Describe the Delete Function in MVC that are used to Delete the Selected Rows.

in which we provide Facility to user that is user can just click on Header checkbox and select all Row or Record that are Exist in Gridview and when click on Delete button then all selected or checked rows are deleted. we also provide a confirmation box before deleting the record same as provide in Gmail Inbox.

For Example:-

            [HttpPost]
        public ActionResult Assign(FormCollection form)
        {
            //get collection of selected ids
            var chckedValues = form.GetValues("assignChkBx");

            //You can use each object if u wish from id
            foreach (var id in chckedValues)
            {
                poll p = new poll();
                var pp =(from ss in dc.polls where ss.Id == Convert.ToInt32(id) select ss).First();
                dc.polls.DeleteOnSubmit(pp);
                dc.SubmitChanges();
                //get object example..  Customer Customer = Customers.find(id);
                //Your Method here like send an item to customer
            }
            return RedirectToAction("index");
        }

 Also how to Display Header CheckBox in WebGrid in MVC code are as follows:

grid.Column(header: "{CheckBoxHeading}",  format:@<text><input class="box"  id="assignChkBx"name="assignChkBx" type="checkbox" value="@item.Id"/></text>),

Rows. Before used this Example you have to create a table in Database are as Follow:



MVC Registration form with all Validation in MVC client and server side validation in MVC4

Insert,Update,Delete in Gridview without postback CRUD operation without refresh the page


Upload multiple Files with Progressbar upload multiple file at a time with progressbar


upload image in database using Image Datatype upload image in database having datatype is image

To Download Complete project then click on Below Download Image Link
download here!


Step 1:-Create Controller in Controller Folder with name DeletemultipleController and paste the below code in it.


DeletemultipleController.cs:-



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Deletemultiplerecord.Models;
using System.ComponentModel.DataAnnotations;


namespace Deletemultiplerecord.Controllers
{
    public class DeleteMultipleController : Controller
    {
        //
        // GET: /DeleteMultiple/
        DataClasses1DataContext dc = new DataClasses1DataContext();
        public ActionResult Index()
        {
            var list = (from p in dc.polls select p).ToList();
            return View(list);
        }
        [HttpPost]
        public ActionResult Assign(FormCollection form)
        {
            //get collection of selected ids
            var chckedValues = form.GetValues("assignChkBx");

            //You can use each object if u wish from id
            foreach (var id in chckedValues)
            {
                poll p = new poll();
                var pp =(from ss in dc.polls where ss.Id == Convert.ToInt32(id) select ss).First();
                dc.polls.DeleteOnSubmit(pp);
                dc.SubmitChanges();
                //get object example..  Customer Customer = Customers.find(id);
                //Your Method here like send an item to customer
            }
            return RedirectToAction("index");
        }
        //
        // GET: /DeleteMultiple/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /DeleteMultiple/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /DeleteMultiple/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /DeleteMultiple/Edit/5

        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /DeleteMultiple/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /DeleteMultiple/Delete/5

        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /DeleteMultiple/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}



Step 2:- Create view for DeletemultipleController and paste the below code in it.


Index.cshtml:-



@model IEnumerable<Deletemultiplerecord.Models.poll>

@{
    ViewBag.Title = "Index";
}
<!DOCTYPE html>

<html>
<head>
    <title>WebgridSample</title>
    <script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
     
 

        //Select/Deselect all checkboxs in the grid
        $(document).ready(function () {
            $("#allBox").click(function () {
                $(".box").attr("checked", $(this).attr("checked") ? true : false);
            });
         
         
        });
</script>
    <style type="text/css">
        .webGrid { margin: 4px; border-collapse: collapse; width: 500px;  background-color:#FCFCFC;}
        .header { background-color: #C1D4E6; font-weight: bold; color: #FFF; }
        .webGrid th, .webGrid td { border: 1px solid #C0C0C0; padding: 5px; }
        .alt { background-color: #E4E9F5; color: #000; }
        .gridHead a:hover {text-decoration:underline;}
        .description { width:auto}
        .select{background-color: #389DF5}
    </style>
</head>
<body>
    <p>
    @Html.ActionLink("Create New", "Create")
</p>
    @{
        Deletemultiplerecord.Models.poll product = new Deletemultiplerecord.Models.poll();
}
    @{
    var grid = new WebGrid(Model, canPage: true, rowsPerPage: 10, selectionFieldName: "selectedRow",ajaxUpdateContainerId: "gridContent");
        grid.Pager(WebGridPagerModes.NextPrevious);}
     @using (Html.BeginForm("Assign", "Deletemultiple"))
   {
        <div id="gridContent">
          




            @MvcHtmlString.Create(grid.GetHtml(tableStyle: "webGrid",
           
                headerStyle: "header",
                alternatingRowStyle: "alt",
                selectedRowStyle: "select",
    fillEmptyRows: false,
 
 
    footerStyle: "footer",
    mode: WebGridPagerModes.All,
    firstText: "<< First",
    previousText: "< Prev",
    nextText: "Next >",
    lastText: "Last >>",

    columns: grid.Columns(
         grid.Column(header: "{CheckBoxHeading}",  format:@<text><input class="box"  id="assignChkBx"name="assignChkBx" type="checkbox" value="@item.Id"/></text>),
            grid.Column("ID", canSort: true, style: "Id"),
        grid.Column("Name", canSort: true, style: "Name"),
        grid.Column("Question", canSort: true, style: "Question"),
       
         grid.Column("", header: "Actions", format: @<text>
                 @Html.ActionLink("Edit",   "Edit",   new { id=item.Id} )
                  @Html.ActionLink("Delete", "Delete", new { id=item.Id} )
                </text>
      )
)).ToString().Replace("{CheckBoxHeading}", "<input type='checkbox' id='allBox'/>")             
             
),
          
        </div>   
    <p><input type ="submit" value ="Assign" /></p>
     }
</body>
</html>    


Step 3:- Add Link For the DeletemultipleController in  Layout.cshtml in Shared Folder with Following code


<li>@Html.ActionLink("DeleteMultiple", "Index", "DeleteMultiple")</li>
 
This entry was posted in :

6 comments:

  1. how to insert selected chekbox value in grid through database using mvc

    ReplyDelete
  2. var chckedValues = form.GetValues("assignChkBx");

    //You can use each object if u wish from id
    foreach (var id in chckedValues)
    {
    //your code here
    }

    ReplyDelete
  3. How to show the pop up(confirmation) window, Are you sure..?

    ReplyDelete
    Replies
    1. Display confirm popup for delete record
      http://aspsolutionkirit.blogspot.in/2013/05/display-confirm-box-when-click-on.html

      Delete
  4. very nice.....

    ReplyDelete