Delete multiple rows (records) in Entity Framework using ASP.Net MVC

I’ll demonstrate how to delete multiple rows (records) in ASP.Net MVC using Entity Framework in this article.

Database

I used the following table, Customers, which has the following schema. An auto-increment (identity) column is called CustomerId.

Entity Framework Model

Once the Entity Framework is configured and connected to the database table, the Model will look as shown below.

Controller

There are two Action methods in the Controller.
GET operation handling action method
All of the Customers table records are returned to the View as a Generic List collection within this Action method.

Procedure for Bulk Delete
An Integer Array containing various CustomerId values is sent as a parameter to this Action function.
Using Entity Framework, a loop is run over the array’s CustomerId values, deleting one by one each Customer record from the database.

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        CustomersEntities entities = new CustomersEntities();
        List<Customer> customers = entities.Customers.ToList();
        return View(customers.ToList());
    }
 
    [HttpPost]
    public ActionResult DeleteCustomers(int[] customerIds)
    {
        using (CustomersEntities entities = new CustomersEntities())
        {
            foreach (int customerId in customerIds)
            {
                Customer customer = (from c in entities.Customers
                                     where c.CustomerId == customerId
                                     select c).FirstOrDefault();
                entities.Customers.Remove(customer);
            }
            entities.SaveChanges();
        }
 
        return new EmptyResult();
    }
}

View

The Customer Entity is declared as IEnumerable inside the View in the very first line, indicating that the Model will be made available as a Collection.
The model, which is an IEnumerable collection of Customer Entity class objects, is used as the source when the WebGrid is initially created.

Checkbox Adding to WebGrid Row
The CustomerID field value is assigned to the checkbox’s value attribute, which is structured to display a checkbox in WebGrid’s first column.

Checkbox Added to WebGrid Header Row

Since there is no easy method to add a CheckBox directly to the WebGrid’s Header Row, a dynamic CheckBox is constructed and added to the row’s first cell using jQuery.

When the Header Row CheckBox is checked (selected)

The Row CheckBoxes should be checked as well.
jQuery’s Click event handler is given access to the Header Row CheckBox. jQuery is used to check (select) all of the row checkboxes when the header row checkbox is checked (selected).

Additionally, using jQuery, when the Header Row CheckBox is unchecked (deselected), all of the row checkboxes follow suit.

When all of the row checkboxes are checked (selected), check the header row checkbox.
A jQuery Click event handler is assigned to every Row CheckBox. A check is made to see if all Row CheckBoxes are checked whenever any Row CheckBox is checked (selected). The Header Row CheckBox is checked (selected) if the response is “Yes,” otherwise, it is unchecked (deselected).

Bulk Multiple checked (selected) rows can be deleted from the web grid.
The checked (selected) CheckBoxes are referenced when the Delete button is clicked, and a JavaScript Confirmation Box is presented.
By iterating over the checked (selected) CheckBoxes and retrieving the CustomerId value from the WebGrid Row to which each CheckBox belongs, an Array is created if the Confirmation Box answer is True.
Finally, checked (selected) Rows are deleted from the WebGrid by sending the Array to the Controller’s Action function via jQuery AJAX.

@model IEnumerable<Customer>
 
@{
    Layout = null;
    WebGrid webGrid = new WebGrid(source: Model, canPage: false, canSort: false);
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }
 
        .Grid {
            border: 1px solid #ccc;
            border-collapse: collapse;
        }
 
        .Grid th {
            background-color: #F7F7F7;
            font-weight: bold;
        }
 
        .Grid th, .Grid td {
            padding: 5px;
            border: 1px solid #ccc;
        }
 
        .Grid td:not(:first-child) {
            min-width: 80px;
        }
 
        .Grid, .Grid table td {
            border: 0px solid #ccc;
        }
 
        .Grid th a, .Grid th a:visited {
            color: #333;
        }
    </style>
</head>
<body>
    @webGrid.GetHtml(
        htmlAttributes: new { @id = "WebGrid", @class = "Grid" },
        columns: webGrid.Columns(
                     webGrid.Column(null, null, format: @<text><input type="checkbox" name="chkRow" value="@item.CustomerID" /></text>),
                     webGrid.Column("CustomerId", "Customer Id"),
                     webGrid.Column("Name", "Name"),
                     webGrid.Column("Country", "Country")))
    <br/>
    <input type="button" id="btnDelete" value="Delete" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="https://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
    <script type="text/javascript">
        $(function () {
            //Create the CheckBox element.
            var chkHeader = $("<input type = checkbox id = 'chkHeader' />");
 
            //Append it to the First cell of Header Row.
            $("#WebGrid th:first-child").append(chkHeader);
 
            //Assign Click event handler to the Header Row CheckBox.
            chkHeader.click(function () {
                if ($(this).is(":checked")) {
                    //If the Header Row CheckBox is checked, check all Row CheckBoxes.
                    $("#WebGrid td input[type=checkBox]").attr("checked", "checked");
                } else {
                    //If the Header Row CheckBox is NOT checked, uncheck all Row CheckBoxes.
                    $("#WebGrid td input[type=checkBox]").removeAttr("checked");
                }
            });
 
            //Assign Click event handler to each Row CheckBox.
            $("#WebGrid input[name=chkRow]").click(function () {
                UpdateHeaderRowCheckBox(chkHeader);
            });
 
            //Retain selection of Header Row CheckBox.
            UpdateHeaderRowCheckBox(chkHeader);
        });
 
        function UpdateHeaderRowCheckBox(chkHeader) {
            if ($("#WebGrid td input[type=checkBox]:checked").length == $("#WebGrid td input[type=checkBox]").length) {
                //If all the Row CheckBoxes are checked, check the Header Row CheckBox.
                chkHeader.attr("checked", "checked");
            } else {
                //Even if one of the Row CheckBoxes is NOT checked, uncheck the Header Row CheckBox.
                chkHeader.removeAttr("checked");
            }
        }
 
        //Delete event handler.
        $("body").on("click", "#btnDelete", function () {
            //Get all the Checked CheckBoxes.
            var checked = $("#WebGrid td input[type=checkBox]:checked");
            if (checked.length > 0) {
 
                //Display Confirmation Message.
                if (confirm("Do you want to delete " + checked.length + " row(s)?")) {
 
                    //Loop and build an Array of CustomerId to be deleted.
                    var customerIds = [];
                    checked.each(function () {
                        var customerId = parseInt($(this).closest("tr").find("td").eq(1).html());
                        customerIds.push(customerId);
                    });
 
                    //Call Delete Action method.
                    $.ajax({
                        type: "POST",
                        url: "/Home/DeleteCustomers",
                        data: '{customerIds: ' + JSON.stringify(customerIds) + '}',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (response) {
                            checked.each(function () {
                                var row = $(this).closest("tr");
                                if ($("#WebGrid TBODY tr").length == 1) {
                                    row.find("td").html("&nbsp;");
                                    row.find("input").hide();
                                } else {
                                    row.remove();
                                }
                            });
                        }
                    });
                }
            }
        });
    </script>
</body>
</html>

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories