In this article I will explain with an example, how to delete multiple rows (records) using Entity Framework Code First Approach in ASP.Net MVC.
 
 
Database
Following is the Customers Table generated using Entity Framework Code First Approach.
Generated Customers Table Schema
Entity Framework Code First Approach: Delete multiple rows (records) in ASP.Net MVC
 
Inserted Records in Customers Table
Entity Framework Code First Approach: Delete multiple rows (records) in ASP.Net MVC
 
 
Namespaces
You will need to import the following namespaces.
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
 
 
Model
Following is the Model class Customer.
It is decorated with the Table Data Annotation. It is used to override the default Table name in the Database.
The Model class consists of three properties.
CustomerId
The property CustomerId is decorated with the following two Data Annotation attributes:
Key – It is used to apply the Primary Key constraint to the Column.
DatabaseGenerated – It is used to make the column as an Identity column in the Table i.e. the column that generates its value automatically when record inserted in the table.
 
Name and Country
The properties Name and Country are decorated with the following two Data Annotation attributes:
Required – It sets the column as NOT NULL in the Table which means the column will not accept NULL values.
StringLength – It sets the value of the maximum number of characters allowed in the column. Basically, it is the length of the Field.
[Table("Customers")]
public class Customer
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CustomerId { get; set; }
 
    [Required]
    [StringLength(100)]
    public string Name { get; set; }
 
    [Required]
    [StringLength(50)]
    public string Country { get; set; }
}
 
 
Database Context
Following is the Database Context class, CustomerDBContext. The Connection String is fetched from the Web.Config file using the key.
Note: For more details about Database Context class, please refer my article ASP.Net MVC: Entity Framework Code First Approach example.
 
using System.Data.Entity;
 
public class CustomerDBContext : DbContext
{
    public CustomerDBContext() : base("name=constr")
    {
        // The Database is initialized and created.
        Database.SetInitializer(new CreateDatabaseIfNotExists<CustomerDBContext>());
    }
 
    // A DbSet for each Entity (Table) needs to be added.
    public DbSet<Customer> Customers { get; set; }
 
    // Add a DbSet for each entity type that you want to include in your model.
 
    protected override void OnModelCreating(DbModelBuilder ModelBuilder)
    {
        base.OnModelCreating(ModelBuilder);
    }
}
 
 
Controller
The Controller consists of following Action method.
Action method for handling GET operation
Inside this Action method, a check is performed whether records are present or not in the Customers table in Database.
If the Customers table is empty, then dummy records are inserted into the Customers CustomerDBContext using the Add method and the SaveChanges method is called which saves all changes made in the database table.
Finally, the records are fetched from the Customers table using Entity Framework Code First Approach and returned to the View.
 
Action method for handling POST operation for Deleting
Inside this Action method, an Integer Array containing multiple CustomerId values is received as parameter.
A loop is executed over the CustomerId values in the array and finally, one by one each Customer record is deleted from the database using Entity Framework.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        using (CustomerDBContext context = new CustomerDBContext())
        {
            if (context.Customers.ToList().Count == 0)
            {
                // Adding Dummy data.
                context.Customers.Add(new Customer() { Name = "John Hammond", Country = "United States" });
                context.Customers.Add(new Customer() { Name = "Mudassar Khan", Country = "India" });
                context.Customers.Add(new Customer() { Name = "Suzanne Mathews", Country = "France" });
                context.Customers.Add(new Customer() { Name = "Robert Schidner", Country = "Russia" });
 
                context.SaveChanges();
            }
 
            return View(context.Customers.ToList());
        }
    }
 
    [HttpPost]
    public ActionResult DeleteCustomers(int[] customerIds)
    {
        using (CustomerDBContext context = new CustomerDBContext())
        {
            foreach (int customerId in customerIds)
            {
                Customer customer = (from c in context.Customers
                                     where c.CustomerId == customerId
                                     select c).FirstOrDefault();
                context.Customers.Remove(customer);
            }
 
            context.SaveChanges();
        }
 
        return new EmptyResult();
    }
}
 
 
View
Inside the View, in the very first line the Customer Model is declared as IEnumerable which specifies that it will be available as a Collection.
Displaying the Records
For displaying the records, a WebGrid is used. The WebGrid is initialized with the Model i.e. IEnumerable collection of Customer Model class objects as source.
 
Adding CheckBox to WebGrid Row
The first column in WebGrid is formatted to display a CheckBox and the CustomerId field value is assigned to the value attribute of the CheckBox.
 
Adding CheckBox to WebGrid Header Row
There is no direct way to add a CheckBox to the Header Row of WebGrid and hence, using jQuery a dynamic CheckBox is created and it is appended to the first cell of the Header row of the WebGrid.
 
Check (Select) Row CheckBoxes when the Header Row CheckBox is checked (selected)
The Header Row CheckBox is assigned a jQuery Click event handler. When the Header Row CheckBox is checked (selected), all the row CheckBoxes are checked (selected) using jQuery.
And in similar way, when the Header Row CheckBox is unchecked (deselected), all the row CheckBoxes are unchecked (deselected) using jQuery.
 
Check (Select) Header Row CheckBox when the all the Row CheckBoxes are checked (selected)
Each Row CheckBox is assigned a jQuery Click event handler. When any Row CheckBox is checked (selected), a check is performed to find whether all Row CheckBoxes are checked.
If the answer is Yes, then the Header Row CheckBox is checked (selected) else the Header Row CheckBox is unchecked (deselected).
 
Bulk Delete multiple checked (selected) Rows from WebGrid
When the Delete button is clicked, all the checked (selected) CheckBoxes are referenced and a JavaScript Confirmation Box is displayed.
If the Confirmation Box response is True, then an Array is built by looping through the checked (selected) CheckBoxes and fetching the CustomerId value from the WebGrid Row to which the CheckBox belongs.
Finally, the Array is sent to the Controller’s Action method using jQuery AJAX and checked (selected) Rows are removed from the WebGrid.
@model IEnumerable<EF_CodeFirst_Bulk_Delete_MVC.Models.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; }
        .Gridtha, .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">
        $(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();
                                }
                            });
                        },
                        error: function (response) {
                            alert(response.responseText);
                        }
                    });
                }
            }
        });
    </script>
</body>
</html>
 
 
Screenshot
Entity Framework Code First Approach: Delete multiple rows (records) in ASP.Net MVC
 
 
Downloads