Search code examples
asp.netjavascriptpagemethods

Pass Array of JavaScript objects to PageMethod


Here's the situation: I would like to iterate through a table with input controls, collect up the values and then submit them to an ASP.NET PageMethod to save the data to the database. I have the collection all figured out but am getting an error that the string can't be converted to a Dictionary<string, object>.

So I end up with something like this being passed to a method with the below signature

[
{ 'id': '383840923', 'name': 'fred', 'car':'honda' },
{ 'id': '243', 'name': 'joe', 'car':'honda' },
{ 'id': '4323423', 'name': 'paul', 'car':'honda' },
{ 'id': '38384234230923', 'name': 'ted', 'car':'honda' },
]

public static bool SaveData(Dictionary<string, object>[] items) {...}

I know that I can pass whole class objects back and forth if properly declared and ASP.NET will handle the conversions for me, but I don't need the whole class being passed, only a couple of the properties.

Edit: I'm using jQuery to do the post back to the server.

What am I doing wrong here?


Solution

  • I figured out what the problem was. I was wrapping the array in quotes before sending it in as part of the $.ajax call so it was being treated as a string instead of an array.

    $.ajax({
        type: "POST",
        url: "<%= Response.ApplyAppPathModifier(Request.Path) %>/UpdateAcademicItems",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: "{'items': **'**" + $.toJSON(items) + "**'**}",
        success: function(data) {
            if(false != data.d) {
                alert('we did it');
            } else {
                alert ('flop');
            }
        },
        error: function() {
            alert('Failed to save Program Items');
        }
    });