views:

28

answers:

2

Hi,

As it is now I create a JavaScript object and then stringify it, put it in a hidden textbox and my code behind can read this string. I then use JSON.NET to parse the string which works fine. I now try to use ajax to post it to my web service but have some issues with how to send the string. I have tried many ways but gets the common errors like

Invalid JSON primitive: myString.

So I checked this out http://encosia.com/2010/05/31/asmx-scriptservice-mistake-invalid-json-primitive/ and it works with hard coded values but I want to use a variable.

JavaScsript to create the object:

for (var i = 0; i < results.rows.length; i++) {
        var row = results.rows.item(i);
    var customer = new Object();

        customer.id = row['id']
        customer.name = row['name']

    var customerString = JSON.stringify(customer);

    $.ajax({
        type: "POST",
        url: "synchronise.asmx/synchroniseCustomers",
        data: "synchroniseCustomers: " + customerString,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
                    error: function (xhr, status) {
                alert("An error occurred: " + status);
            },
        success: function (msg) {
            alert("success");
        }
    });
}

WebMethod:

 public void synchroniseCustomers(string customerString)
        {
            JObject o = JObject.Parse(customerString);
            string id = (string)o["id"];
            string name = (string)o["name"];

If I use data: '{ FirstName: "Dave", LastName: "Ward" }' in the example above it works but I wish to pass on a string instead.

Any suggestions?

Thanks

A: 

Your data parameter needs to be enclosed in {} if you're passing json and your webmethod needs to be visible to script by adding a decorator. Take a look at this blog entry I wrote a while back - it has an example. I also found this article helpful.

The attribute you should add to your asmx class is [System.Web.Script.Services.ScriptService] and you will need to add [System.Web.Script.Services.ScriptMethod] to your webmethod if you haven't already.

...btw you are passing a string; it's just in json format. If you want to use a parameter passing mechanism other than json you can leave contentType off your call and pass your parameters like below although you'll have to verify that your asmx will parse the parameters ok (MVC has no qualms with it :)

data:"FirstName=David&LastName=Ward"
Tahbaza
yeah as I wrote it works with hard coded values but I'm trying to post a string instead.
Morgan
things is I have about 50 variables so it's easier to stringify them and then parse it in the web service instead of having to update fields (if I need to that is) in many places.
Morgan
in that case look into the jquery serialize() method to serialize your form and send it all [http://api.jquery.com/serialize/]
Tahbaza
A: 

You're pretty close, but you'd need to send that like this:

data: '{"synchroniseCustomers": ' + customerString + '}'

Also, there's no need to accept it as a string and manually deserialize the JSON on the .NET side. .NET will handle all of that automatically if you declare the input type as a matching server-side structure.

This should help with what you're trying to do there: http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/

Dave Ward
Hi Dave, with data: '{"synchroniseCustomers": ' + customerString + '}'I still get the same error, I tried to do "synchroniseCustomers:" (change place of the colon) but then got the error Invalid object passed in, \u0027:\u0027 or \u0027}\u0027 expected.
Morgan
I had a look at that article yesterday and didn't get it to work but I did now, thanks.
Morgan