Passing a list of ints to WebMethod using jQuery and ajax.

Posted by birdus on Stack Overflow See other posts from Stack Overflow or by birdus
Published on 2010-12-24T01:57:21Z Indexed on 2010/12/24 2:54 UTC
Read the original article Hit count: 305

Filed under:
|
|

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

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about jQuery