I have an array I build up when a row is selected in my bootstrap data table. I then need to pass this from my view to the controller which is going to fire up a partial view. However when I execute the code I get null reference exception in my controller. The code in the controller is just a placeholder for the actual use but is there to show I intend to be looping the array when it is loaded through. Any ideas as to why it would show NULL even though I can see in debug it has values.
AJAX:
function MoveSelected() {
$.ajax({
type: "Get",
url: '@Url.Action("MoveSelectedRoute", "Transport")',
data: { orders: completeArray },
success: function (data) {
$('#detail_MoveSelectedOrders').html(data);
$('#modalMoveSelectedOrders').modal('show');
}
})
}
Controller:
public ActionResult MoveSelectedRoute(string[] orders)
{
string OrdersToMove = string.Empty;
foreach (string row in orders)
{
string orderNo = orders.ToString().PadLeft(10, '0');
if (OrdersToMove == string.Empty)
{
OrdersToMove = orderNo;
}
else
OrdersToMove = OrdersToMove + "," + orderNo;
}
}
You need to add the traditional: true ajax option to post back an array to the collection.
$.ajax({
type: "Get",
url: '@Url.Action("MoveSelectedRoute", "Transport")',
data: { orders: completeArray },
traditional true,
success: function (data) {
....
}
})
Note the traditional: true option only works for simple arrays.
And alternative would be to stringify the data, set the content type to application/json and make a POST rather than a GET
$.ajax({
type: "Get",
url: '@Url.Action("MoveSelectedRoute", "Transport")',
data: JSON.stringify({ orders: completeArray }),
contentType: "application/json; charset=utf-8"
success: function (data) {
....
}
})
The final alternative is to generate send the values with collection indexers
var data = {
orders[0] = 'abc',
orders[1] = 'xyz',
orders[2] = '...'
}
$.ajax({
type: "Get",
url: '@Url.Action("MoveSelectedRoute", "Transport")',
data: data,
success: function (data) {
....
}
})
You have to use JSON.stringify({ orders: completeArray }) and your C# code will map your array with its parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With