Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a string array from an ajax function to mvc controller

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;
    }
}
like image 399
UnintentionalWebDev Avatar asked Dec 13 '25 10:12

UnintentionalWebDev


2 Answers

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.

like image 41
Pierre-Adrien Maison Avatar answered Dec 15 '25 23:12

Pierre-Adrien Maison