ASP.Net MVC How To Handle Multiple Checkboxes With Views/Actions… jQuery too!

Just a note, this is kind of an add on to this post but it’s a much more simple (HOSTED) example and also deals with doing the whole check box thing with jQuery.

So one of the things I ran into some what recently was a grid… a grid with a death wish and a thirst for revenge. It also has a bunch of check boxes to allow multiple row deletes.

Now there might be a moment of panic and doubt (Or doubt and panic, everyone reacts differently) when you realize you no longer have those cushy grid postback events. WHAT ARE YOU GOING TO DO???? Well first you’re going to feel disgust over your profuse sweating, cause lets be honest you’re pretty gross. Then you’re going to read on and find that all your panic, fun as it can be, was for nothing. Why? Because you have me… and not in some weird love kind of way because I don’t even know you. More of a “You can count on me because I’m like that cool older brother you never had and because of which you ended up a social degenerate ie a programmer” kind of way.

Now to start I’ve already hosted both the code and a working example:

Actual running thing on teh webz.

Hosted code

Because I’m such a nice guy. (And that’s true, I can list at least five people who aren’t my mom who can attest to that.) However, I wouldn’t be the nice guy that I am if I weren’t going to at least explain some of the code.

There are two ways I handle this situation in the example I hosted, one is with a form, action, and post back. The other is with jquery and an asynchronous call. Both are actually pretty easy to pull off.

First let’s look at the post back version. The mark up looks a little somethin’ like dis:

  <form action="/Test/CheckForIds/" method="post">
      <input type="checkbox" name="IdList" value="1"  />
      <input type="checkbox" name="IdList" value="2" />
      <input type="checkbox" name="IdList" value="3" />
      <input type="checkbox" name="IdList" value="4" />
      <input type="submit" value="go" />

Looks like your standard form and if you’ve used MVC at all, you should be used to seeing something like that. The only thing of interest is that the checkboxes don’t have ids and do share the same name. There’s a good reason for the second one. Here’s the action method:

  public ActionResult CheckForIds(Int32[] idList)
     return View(idList);

Now it makes more sense, doesn’t it? The name attribute on the checkbox directly corresponds to the name of the array parameter. THAT’S AMAZING!!!1 Actually, kidding aside it is kind of nice. Not only does it match the checkboxes to the parameter, it also treats the values of the checkboxes (Checked ones) as a list of integers. Pretty slick.

And honestly, that’s about all it takes for traditional posting.

Now for the jQuery part:

    <input type="checkbox" name="JqueryIdList" value="1"  />
    <input type="checkbox" name="JqueryIdList" value="2" />
    <input type="checkbox" name="JqueryIdList" value="3" />
    <input type="checkbox" name="JqueryIdList" value="4" />
  <div onclick="getIds('JqueryIdList');">

Wow, looks about the same. Go figure. Well that’s pretty much because the way hard part is the javascript itself.

  function getIds(checkList)
    var idList = new Array();
    var loopCounter = 0;
    //find all the checked checkboxes
    jQuery("input[name=" + checkList + "]:checked").each
        //fill the array with the values
        idList[loopCounter] = jQuery(this).val();
        loopCounter += 1;
    //Send the list off
    jQuery.getJSON("/Test/CheckForIdsJson/", { idList: idList }, idsGotten);

Ok maybe it wasn’t that hard or hard at all. But um… And here’s the action method:

  public ActionResult CheckForIdsJson(Int32[] idList)
    JsonResult result = new JsonResult();
    result.Data = idList;

    return result;

So again, the same signature. Amazing huh?

Side note:

When I was eating this morning in front of the television (Chocolate shredded mini wheats if you must know.) I came upon the good ole classic Iron Eagle. I never really thought about how utterly f-ing insane that movie was until now though, mostly because I haven’t seen it since I was a kid. I guess back then I could completely buy into the idea of some 17 year old, who can’t make it into the Air Force Academy, suiting up and learning to use (At the time) the most complicated fighter the US had to offer within what? one whole montage, steal a 18 million dollar plane (Planes were cheap back then), fly into crazy dangerous territory, get past who knows how many trained professionals, save his dad, and nothing really comes of it. Actually I think if I remember (as I didn’t get to watch the whole thing this time) he gets a place in the academy from this. IT’S A COMPLETELY BELIEVABLE STORY! The best part about it is that apparently between the time of the first and second movie his skills had depleted so fast that he gets popped at the beginning of the second one. I guess without the Saving Dad mojo, he’s just not the same. Tip your glass to good ole Thumper.

I really miss the 80s where movies didn’t really need to make any sense as long as they had some soundtrack filled with crazy obscure bands playing at random times in the movies itself followed by the movie characters commenting how great the music is.

15 thoughts on “ASP.Net MVC How To Handle Multiple Checkboxes With Views/Actions… jQuery too!”

  1. Thats really useful to know, thanks for sharing that. I did wonder though, how did you get the grid to work in the end, did you create a htmlhelper class to generate it? I’m trying to create a grid like the one in your screenshot using the MVC Contrib Grid and am struggling to add the checkboxes to it.

  2. The old fashioned way. I build all my grids in a for loop using divs and styles. It takes more work in the begining to set up a sort of system (mostly the creating generic grid styles) but in the end it’s worked out pretty well. (Copy and paste are my friends) I generally try to stay away from stuff I don’t build because of situations like yours. I hate not knowing exactly how to change things if I need to. Beyond that, I think I have a much better understanding of styles and html because of it.

    1. Well I probably should have named it better. IdsGotten is actually your method to call once the json has been returned. So you would make a function named IdsGotten (Though grammatically I wouldn’t suggest this) that has a signature of:

      function IdsGotten(data)

      And within that you would treat data as a list and therefore will be able to iterate through it.

  3. Hi.. I have a question… the JQuery code works very well…and I can see that the idList has the numbers 4 and 6…which are the values of the checked checkboxes… this only problem is in the controller… the idList is null… Should the array in the controller be of String type… or maybe it should be a List… or maybe I need a serializedArray???
    Any help??

  4. I love your banter.

    Don’t let “tools” ever get you down.

    Your stuff “rocks” (GO USA 😉 ) Or (its rather entertaining [ en-GB locaiSed version)

    Thanks for sharing.

    1. I’m not sure to be happy that you understand my insanity or sad… because you understand my insanity. Either way… you “rock”.

  5. How to select all values of a ASP.NET MVC 2.0 ListBox when a checkBox is clicked ?

  6. Thanks for the helpful posts on checkbox lists and jQuery, you saved me quite some time this morning 😀

  7. Oh and…
    I needed to use “jQuery.ajaxSettings.traditional = true;” to allow jQuery to pass on the int[] array, without that statement my controller action was receiving a null.

Comments are closed.