Using jQuery to Handle Checkboxes in ASP.NET MVC 3

Let’s say we have a simple to-do list application in ASP.NET MVC which displays a table of open tasks. And below that table, we display a list of completed tasks.

Task List

The scenario is pretty straight forward – when a user clicks on an open task check box (to mark it complete) we need to update the database record for that task and then move it to the completed tasks list below. And vice versa – if a user changes their mind and unchecks the completed task, then we need to update the database record again and move that task back up to the open task table. There’s no submit button or form here – it’s going to be something we’ll handle dynamically with one click of a checkbox.

Here’s part of the HTML generated by our Razor view. Each task has a unique ID e.g. ‘checkbox1’ based on the task ID in the database i.e. 1. I just added the ‘checkbox’ prefix to avoid confusion with lots of ‘vague’ numbered IDs all over the place in the HTML.

 
 Buy milk
 
 Write status report
 
 Pickup dry cleaning

  • Schedule meeting with BobDelete
  • First, we need to get our jQuery code working to handle the check and uncheck events for any of these tasks. All we’re doing here is getting the ID of the task that’s being checked (stripping out the ‘checkbox’ prefix), determining if a checkbox was checked or unchecked and then then passing that ID to the relevant action method in the Item controller i.e. “Complete” or “Incomplete” action method:

    
    $('input[type=checkbox]').click(function () {
    var itemid = this.id.substring(8);
    if ($(this).is(':checked')) {
    $(window.location).attr("href", "/item/complete/" + itemid);
    } else {
    $(window.location).attr("href", "/item/incomplete/" + itemid);
    }
    })
    
    

    The “Complete” action method finds the record in the database using the ID that was passed to it from the jQuery function, updates the “Completed” column to “Y”, saves the database changes and then redirects to the “Index” action method (which displays the Razor view shown above).

    
    public ActionResult Complete(int id)
    {
    Item item = db.Items.Find(id);
    
    if ((item == null)
    {
    return View("NotFound");
    }
    
    item.Completed = "Y";
    db.SaveChanges();
    return RedirectToAction("Index");
    }
    
    

    The “Incomplete” action method basically does the same thing as the “Complete” action method above, but changes the “Completed” column value to “N” i.e. marks the task as open again.

    I’m not sure if doing a redirect from the jQuery function to the relevant action method is the best way to handle this (versus a Post), but it seems to work okay. The next step will be to use some Ajax to just update the table & list without reloading the entire page, but I’ll leave that for another day.