Passing a list of ints to WebMethod using jQuery and ajax.
- by birdus
I'm working on a web page (ASP.NET 4.0) and am just starting simple to try and get this ajax call working (I'm an ajax/jQuery neophyte) and I'm getting an error on the call. Here's the js:
    var TestParams = new Object;
    TestParams.Items = new Object;
    TestParams.Items[0] = 1;
    TestParams.Items[1] = 5;
    TestParams.Items[2] = 10;
var finalObj = JSON.stringify(TestParams);
var _url = 'AdvancedSearch.aspx/TestMethod';
$(document).ready(function ()
{
    $.ajax({
        type: "POST",
        url: _url,
        data: finalObj,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg)
        {
            $(".main").html(msg.d);
        },
        error: function (xhr, ajaxOptions, thrownError)
        {
            alert(thrownError.toString());
        }
    });
Here's the method in my code behind file:
[Serializable]
public class TestParams
{
    public List<int> Items { get; set; }
}
public partial class Search : Page
{
    [WebMethod]
    public static string TestMethod(TestParams testParams)
    {
        // I never hit a breakpoint in here
        // do some stuff
        // return some stuff
        return "";
    }
}
Here's the stringified json I'm sending back:
{"Items":{"0":1,"1":5,"2":10}}
When I run it, I get this error:
  Microsoft JScript runtime error: 'undefined' is null or not an object
It breaks on the error function.
I've also tried this variation on building the json (based on a sample on a website) with this final json:
    var TestParams = new Object;
    TestParams.Positions = new Object;
    TestParams.Positions[0] = 1;
    TestParams.Positions[1] = 5;
    TestParams.Positions[2] = 10;
    var DTO = new Object;
    DTO.positions = TestParams;
    var finalObj = JSON.stringify(DTO)
{"positions":{"Positions":{"0":1,"1":5,"2":10}}}
Same error message.
It doesn't seem like it should be hard to send a list of ints from a web page to my webmethod. Any ideas?
Thanks,
Jay