Joe walter Joe walter - 4 months ago 9
jQuery Question

How to send multiple array with jQuery in MVC.NET?

I have 2 arrays in my Razor view. The first one checked checkboxes and the second is for unchecked. I can send one of them but I don't know how to send both of them. This is my jQuery code:

$(document).ready(function() {
$("#checkAll").click(function() {
$(".checkBox").prop('checked', $(this).prop('checked'));
});
$("#confrim").click(function() {
var selectedIDs = new Array();
var unseletedeIDs = new Array();
$('input:checkbox.checkBox').each(function() {
if ($(this).prop('checked')) {
selectedIDs.push($(this).val());
} else {
unseletedeIDs.push($(this).val());
}
});
var options = {};
options.url = "/Parts/ConfrimAll";
options.type = "POST";
options.data = JSON.stringify(selectedIDs);
options.contentType = "application/json";
options.dataType = "json";
options.success = function(msg) {
alert(msg);
};
options.error = function() {
alert("Error!");
};
$.ajax(options);
});
});


This is the action:

public ActionResult ConfrimAll(int[] SelectedIDs, int[] UnSelectedIDs)
{
foreach (int id in SelectedIDs) {
Part obj = db.Parts.Find(id);
obj.IsOk = true;
db.Entry(obj).State = EntityState.Modified;
}

foreach (int id in UnSelectedIDs)
{
Part objs = db.Parts.Find(id);
db.Parts.Remove(objs);
}
db.SaveChanges();
return Json("yes");
}

Answer

You can provide both array as part of an object to the data parameter of the $.ajax call. Try this:

$("#confrim").click(function() {
    var data = {
        SelectedIDs: [],
        UnSelectedIDs: [],
    }
    $('input:checkbox.checkBox').each(function() {
        data[this.checked ? 'SelectedIDs' : 'UnSelectedIDs'].push(this.value);
    });

    $.ajax({
        url: '/Parts/ConfrimAll',
        type: 'POST',
        data: data,
        success: function(msg) {
            console.log(msg);
        },
        error: function(x, s, e) {
            console.log('Error!');
            console.log(x, s, e);
        }
    });
});

Note that it's much better practice to provide an object to the data parameter as jQuery will then encode it for you to the required format, escaping any special characters as it does it.