Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing complex JSON string to 1 parameter webmethod in c# - desearialize into object (json.net)?

I have been happy serializing with javascript objects into JSON using

         JSON.stringify

And sending along to my "static" webmethod in c#/asp.net and sure enought it arrives .. I need the correct number of parameters hence if my json object has "startDate","endDate","reserve" then my webmethod needs these as parameters.

"Basically with my order object that i have, i have a number of parameters on this object so i would need to use the same number on the webmethod - this is a bit messy??" - I will explain

I have a rather complex "Order" object in javascript and wish to serialize it using stringify and send it along to my webmethod but i don't want to specify all the parameters is there a way round this?

I was hoping for something like this on my webmethod

           public static bool MakeReservation(object order)

Then in my webmethod i only have 1 parameter BUT i can then desearilize this to a true c# object using JSON.NET. I have tried it like this sending the json across but because there is ONLY 1 parameter on my webmethod its failing.

Basically what i am trying to say if i that i want to continue to use my webmethod but i don't want to have to do specify 15 parameters on the webmethod

I want the JSON - String to arrive into my webmethod and then i can decompose it on the server.

Is this possible?

Here is how i am currently sending my JSON to the server (webmethod) using jquery

    var jsonData = JSONNew.stringify(orderObject);

    $.ajax({
        type: "POST",
        url: "MyService.aspx/DoReservation",
        data: jsonData,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            success = true;
        },
        error: function(msg) {
            success = false;
        },
        async: false
    });
like image 775
mark smith Avatar asked Dec 09 '22 20:12

mark smith


1 Answers

If you try to submit an object that looks like this:

JSON.stringify({ endDate: new Date(2009, 10, 10), startDate: new Date() });

it will try and map endDate and startDate to corresponding parameters in your webmethod. Since you only want to accept one single method, I suspect you may get away with it by submitting the following:

JSON.stringify({ order: orderObject });

Which it might reasonably try to assign as a value to the 'order' parameter of your webmethod. Failing that, submitting

JSON.stringify({ order: JSON.stringify(orderObject) });

and then deserializing it using JSON.NET should definitely work, but it's uglier, so try the first example first. That's my best shot.

like image 161
David Hedlund Avatar answered Dec 13 '22 14:12

David Hedlund