Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass list of ints from JavaScript to C# -- I get the list, but it is empty; form data isn't structured properly?

I have my array populated like so:

updateLabels: function () {
    var diagrams = _stage.diagramLayer.getChildren();

    var componentIDs = new Array();

    for (var index = 0; index < diagrams.length; index++) {
        componentIDs.push(diagrams[index].componentID);
    }

    var self = this;
    $.ajax({
        url: '../PlanView/UpdateDiagrams',
        type: 'POST',
        data: { ComponentIDs: JSON.stringify(componentIDs), RackInfo: $('#RackInfoSelect').val() },
        success: function (data) {
            console.log('success');
        },
        error: function () {
            console.log("error");
        }
    });
    },

server side I have this method:

[CompressionFilterAttribute]
public JsonResult UpdateDiagrams(List<int> componentIDs, string rackInfo)
{
    List<object> diagramInformation = new List<object>(componentIDs.Count());
}

my data as it is being passed across the network:

ComponentIDs:[74,445,732,351,348,347,1123,599,600,1053,350,601,602,603,332,99,877,919,349,348,347,347,349,348]
RackInfo:Equipment Weight

I successfully get RackInfo, if I change UpdateDiagrams to expect List<string> then I get a list with one item in it, the entire ComponentIDs string.

What am I doing incorrectly here?

EDIT: I am working under MVC3. I should be able to leverage some sort of automatic deserialization when passing to my controller, I am just not sure how.

SOLUTION: The solution was to wrap my data object in JSON.stringify, not just componentIDs. Even though I can get the RackInfo variable server-side without converting it to JSON.

like image 855
Sean Anderson Avatar asked Mar 20 '12 23:03

Sean Anderson


1 Answers

If you want your posted data to be in JSON format then try something like this. MVC should then be able to deserialise it automatically on the server-side.

$.ajax({
    url: '../PlanView/UpdateDiagrams',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({
        componentIDs: componentIDs,
        rackInfo: $('#RackInfoSelect').val()
    }),
    success: function (data) {
        console.log('success');
    },
    error: function () {
        console.log("error");
    }
});

(I'm unable to test it at the moment, but it should hopefully be along the right lines even if it's not completely bug-free.)

like image 151
LukeH Avatar answered Oct 23 '22 04:10

LukeH