Online courses in ASP.NET MVC / Core, jQuery, Angular, and Design Patterns conducted by Bipin Joshi. Read more...
Learn ASP.NET MVC / Core, jQuery, Angular, and Design Patterns through our online training programs. Courses conducted by Bipin Joshi on weekends. Read more details here.

Select All and Delete using ASP.NET MVC and jQuery Ajax

Sometimes you need to select records for certain action using checkboxes. For example, you may select records for deleting and then delete them from the database. Consider the following screen shot that shows such an example in action.

As you can see there are two ways to select records for deletion:

  • You select checkboxes for rows to be deleted individually.
  • You can check the checkbox placed in the header row to select all the rows. This checkbox toggles the checked state of the other checkboxes.

Once selected you can click on the Delete Selected Customers button to actually delete the records.

Implementing such a functionality is straightforward using ASP.NET MVC, jQuery and Ajax. Let's see how.

As an example we will use Customers table of the Northwind database for this example. You will need to create a model class for the Customers table using EF code first. The Customer class is shown below:

public partial class Customer
    public string CustomerID { get; set; }

    public string CompanyName { get; set; }

    public string ContactName { get; set; }

    public string ContactTitle { get; set; }

    public string Address { get; set; }

    public string City { get; set; }

    public string Region { get; set; }

    public string PostalCode { get; set; }

    public string Country { get; set; }

    public string Phone { get; set; }

    public string Fax { get; set; }

The NorthwindDbContext - the DbContext of our model - is shown below:

public partial class NorthwindDbContext : DbContext
    public NorthwindDbContext()
        : base("name=NorthwindDbContext")

    public virtual DbSet<Customer> Customers { get; set; }

    protected override void OnModelCreating
                (DbModelBuilder modelBuilder)
            .Property(e => e.CustomerID)

Notice that the NorthwindDbContext assumes that the database connection string is stored in web.config with a name of NorthwindDbContext.

Now add HomeController and write Index() and Delete() actions as shown below:

public ActionResult Index()
    using (NorthwindDbContext db = 
                  new NorthwindDbContext())
        var query = from c in db.Customers
                    select c;
        return View(query.ToList());

public ActionResult Delete(string[] customerIDs)
    using (NorthwindDbContext db = 
                        ew NorthwindDbContext())
        foreach (string customerID in customerIDs)
            Customer obj = db.Customers.Find(customerID);
        return Json("All the customers 
                     deleted successfully!");

The code from the Index() action simply picks all the customers from the Customers table and passes them to the Index view for display.

The Delete() action takes a single parameter - array of CustomerIDs to be deleted. The Delete() action will be called through client side jQuery code and while calling the array will be passed to it. The Delete() action simply iterates through the customerIDs array and one-by-one deletes the customers from the database. Finally, a success message is sent back to the caller in JSON format.

Now add Index view and also add a <script> reference to the jQuery library. Then add the following markup in the Index view.

@model List<SelectAllDeleteDemo.Models.Customer>
    <h1>List of Customers</h1>
    <input type="button" id="delete" 
         value="Delete Selected Customers" />
    <br /><br />
    <table border="1" cellpadding="10">
            <th><input type="checkbox" id="checkAll"/></th>
        @foreach(var item in Model)
                <td><input type="checkbox" class="checkBox" 
                     value="@item.CustomerID" /></td>

Notice a few things about this markup:

  • The customer data - CustomerID, CompanyName and Country - is displayed in a table.
  • The header row contains a checkbox whose ID is checkAll
  • Each table row contains a checkbox whose class attribute is set to checkBox. And its value is set to the CustomerID of that row.
  • The button above the table is used to initiate the delete operation and its ID is delete.

Now add a <script> block and write the following jQuery code:

$(document).ready(function () {

    $("#checkAll").click(function () {

    $("#delete").click(function () {
        var selectedIDs = new Array();
        $('input:checkbox.checkBox').each(function () {
            if ($(this).prop('checked')) {

        var options = {};
        options.url = "/home/delete";
        options.type = "POST"; = JSON.stringify(selectedIDs);
        options.contentType = "application/json";
        options.dataType = "json";
        options.success = function (msg) {
        options.error = function () {
            alert("Error while deleting the records!");


The code wires click event handlers for the checkAll checkbox and the delete button. The click event handler of the checkAll checkbox toggles the checked state of all the checkboxes. This is done by selecting the checkboxes using the jQuery class selector. The checkboxes whose class attribute is checkBox are matched and their checked property is toggled. Notice the use of prop() method to do this.

The click event handler of the delete button declares an array variable to store the selected CustomerIDs. It then selects all the checkboxes with CSS class of checkBox. The each() method iterates through these checkboxes. If a checkbox is checked its value is pushed into the array. This way we get all the CustomerIDs into the selectedIDs array. The success callback simply displays the success message returned from the Delete() action.

Then options object is created to hold all the Ajax configuration properties. Notice that url property points to the Delete() action and data property holds the JSON version of the selectedIDs array. Finally, $.ajax() is used to make the Ajax call.

That's it! Run the application and test the functionality.

Bipin Joshi is a software consultant, trainer, author and a yogi having 21+ years of experience in software development. He conducts online courses in ASP.NET MVC / Core, jQuery, AngularJS, and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced Yoga way of life he also teaches Ajapa Meditation to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 02 Feb 2016

Tags : ASP.NET MVC C# jQuery JavaScript