I have a C# method that requires a String[]
array and I use a $.getJSON
call to deliver the parameters to the Method in the Controller.
I am taking the values of Checkboxes that have been selected and passing them back to the Controller, however when I use Stringify
it places if multiple values, together and when I pass the array its self, there are multiple entries, however the receiving String[]
is null.
var array = new Array();
$('#ids:checked').each(function() {
array.push($(this).val())
}
var jsonText = JSON.stringify(array); // I have tried this, but to receive one entry
var dataValues = {
ids: jsonText,
id: $('#idNumber').val(),
orderId: $('#orderId').val()
};
$.getJSON("/path/to/method", dataValues, function(){});
public ActionResult doSomething(String[] ids, Int32 Id, Int32 OrderId)
{
//do something here
}
Thanks for the help.
You are setting the value of ids
to a JSON string; however, the server has no way of knowing that. As far as the server knows, ids
is a string
value, which can't be converted to string[]
.
Instead of converting one value to JSON, you should convert the whole data object to JSON and specify its content-type:
var dataValues = {
ids: array, //the Javascript array, *not* the JSON string
id: $('#idNumber').val(),
orderId: $('#orderId').val()
};
$.ajax({
url: "/path/to/method",
data: JSON.stringify(dataValues),
success: function(){},
contentType: "application/json"
});
I have not posted Arrays back using GET before, I normally use POST, with something like this:
var sData = JSON.stringify({ ids: array});
$.ajax({
url: "/path/to/method",
data: sData,
method: 'POST',
contentType: "application/json; charset=utf-8",
success: function (result) {
},
error: function (result) {
}
});
In your case it might be:
var dataValues = JSON.Stringify({
ids: array,
id: $('#idNumber').val(),
orderId: $('#orderId').val()
});
$.ajax({
url: "/path/to/method",
data: sData,
method: 'GET',
contentType: "application/json; charset=utf-8",
success: function (result) {
},
error: function (result) {
}
});
// $.getJSON("/path/to/method", dataValues, function(){});