2

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

1
  • Sorry about the screwed up formatting on the JavaScript. Not sure what's up with that. Commented Dec 24, 2010 at 1:58

4 Answers 4

4

I tried this and it is working in .NET 3.5. The difference is that after serializing the array is like Items:[1,2] In .aspx

var _url = 'Default.aspx/TestMethod';
            $(document).ready(
                function() {
                    $.ajax(
                    {
                        type: "POST",
                        url: _url,
                        data: '{"i":{"Items":[1,2]} }',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function(msg) {
                            $(".main").html(msg.d);
                        },
                        error: function(xhr, ajaxOptions, thrownError) {
                            debugger;
                            alert(thrownError.toString());
                        }
                    }
                    )
                }
                );

In .cs

[WebMethod]     
    public static string TestMethod(TestParams i)     
    {


        return "whaever";     
    } 

I got the string from this

var serializer = new JavaScriptSerializer();

        var param = new TestParams();
        var list = new List<int> {1, 2};

        param.Items = list;

        string serializedString = serializer.Serialize(param);

Hope this helps.

Sign up to request clarification or add additional context in comments.

4 Comments

I'm not sure where your last code block is in the grand scheme of things and what I should be doing with it.
Actually, I don't think I need your last code block for anything. The problem was with the formatting of the json string I was passing from the JavaScript to the .NET method. Here is your string: '{"i":{"Items":[1,2]} }. The key is that the first string after the opening bracket ("i", in this case) needs to be the same as the parameter name of my method and the next string ("Items") needs to be the same as the property in my class (since I'm declaring a class for the parameter to the method). Thanks!!!
By the way, I also can't use stringify. You just need the square brackets and integers (no quotes) to end up with a List<int> in the WebMethod.
@birdus: I never got the JSON class may be because i am using VS2008. I never saw that the parameter was missing in the javascript.
3

Change 'TestParams.Items = new Object();' to

TestParams.Items = new Array();

Comments

1

The problem may be a missing scriptservice attribute on your codebehind class to make the webmethod accessible from script. See this http://msdn.microsoft.com/en-us/library/system.web.script.services.scriptserviceattribute.aspx.

2 Comments

I'm not calling a WebService, though, so that's not it. Also, my code works if I just pass a string (something like data: "{something: 'blah'}") from the ajax call, assuming the signature of my WebMethod is just: string MethodName(string s).
As I already said, the WebMethod IS accessible from the script, as I am able to call it with a simpler signature, so your suggestion didn't really make sense to me, so no, I didn't try it. But, since you took the time to try and help me, I figured I owed it to you to give it a shot. Alas, it didn't make a difference.
0

I might be wrong but it looks like you should try this:

[Serializable]
public class TestParams
{
    public List<int> Items { get; set; }
}

public partial class Search : Page
{
    [WebMethod]
    public static string TestMethod(List<int> finalObj)
    {
        TestParams testParams = new TestParams { Items = finalObj };

        //Use whatever method you have to return the testParams as JSON 
        return testParams;
    }
}

On you callback you will have to get the data.Items:

success: function (msg)
  {
      $(".main").html(msg.Items);
  },

Hope this helps :)

1 Comment

The problem is that I can't get the list of integers to the WebMethod from the JavaScript, not that I can't return data from the C# class to the web page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.