User987 User987 - 1 month ago 13
jQuery Question

Passing key-value pair jquery array into .NET MVC action

I have an jquery key-value pair array as following:


  • The array is filled when check-boxes are checked

  • If a checkbox is unchecked, item will be removed from there



The code for that part is:

$(document).on('click', '.chkItem', function () {
if ($(this).is(':checked')) {
product_ids[$(this).attr('id')] = "Checked";
} else {
delete product_ids[$(this).attr('id')];
}
});


This works fine, let's head onto the next part. Now I'm trying to send all these ID's from my view into a controller "Analyze" and action "Index", which looks as following:

$(".btnAnalyze").click(function () {
if (jQuery.isEmptyObject(product_ids) == true) {
alert("Array is empty");
}
else {

var postData = { values: product_ids };

$.ajax({
type: "POST",
url: "/Analyze/Index",
data: postData,
success: function (data) {
alert(data.Result);
},
dataType: "json",
traditional: true
});

}
});


And my action looks like following:

public ActionResult Index(List<string> values)
{
string id2= "";
foreach (var id in values)
{
id2= id;
}
// I'm trying to fetch the ID values here that I added into the array, but I'm not sure how...

}


With this current method the contents of List values is

"[object Object]"


which is not what I want.. I need all of the ID's sorted out nicely into the list as I send them to the Action Index...

Can someone help me out with this???

Answer

You're using an object, not an array, and it is thus saying that it's an object. You have two choices:

  1. Use an actual array:

    var product_ids = [];
    $(document).on('click', '.chkItem', function () {
      if ($(this).is(':checked')) {
        product_ids.push($(this).attr('id'));
      } else {
        product_ids.splice(product_ids.indexOf($(this).attr('id')), 1);
      }
    });
    
  2. Continue using an object and use Object.keys to get just the property names (which are the IDs in your code):

    var postData = { values: Object.keys(product_ids) };
    

Personally, I like #1 because it's more explicit that you're capturing the ids of the checked checkboxes, and the values of the object's properties is always "Checked" rather than anything meaningful, but hey, JavaScripts' flexible like that :).