4

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
    });
3
  • I tried this but it is as if i just JSON the object not the STRING var jsonData1 = JSONNew.stringify(orderObject); var myString = jsonData1; var jsonData = JSONNew.stringify(myString); Commented Jul 6, 2009 at 16:51
  • why are you changing the contentType? what happens when you take that out Commented Jul 6, 2009 at 17:09
  • as far as i know you need that in.. the content type?? This is what most tutorials say... I managed to do it ... but i have no idea if its good practice or ?? basically i did this var jsonString = JSONNew.stringify(orderObject); var jsonObject = new Object(); jsonObject.jsonString = jsonString ; var jsonData = JSONNew.stringify(jsonObject); Now i need only 1 parameter on the webmethod which is a string and the json string enters it .. I have no idea if it works yet.. but at least i enter into the webmethod with jsonstring Commented Jul 6, 2009 at 17:12

3 Answers 3

9

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.

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

Comments

4

It's possible. I'm not so good at explaining stuff, I'll just show you my example code:

Javascript:

var Order = function(name, orderid, price) {
this.name = name;
this.orderid = orderid;
this.price = price;}

var pagePath = window.location.pathname;

function setOrder() {
var jsOrder = new Order("Smith", 32, 150);
var jsonText = JSON.stringify({ order: jsOrder });
$.ajax({
    type: "POST",
    url: pagePath + "/SetOrder",
    contentType: "application/json; charset=utf-8",
    data: jsonText,
    dataType: "json",
    success: function(response) {
        alert("wohoo");
    },
    error: function(msg) { alert(msg); }
});
}

C# Code behind

public class Order
{
 public string name { get; set; }
 public int orderid { get; set; }
 public int price { get; set; }
}

[WebMethod]
public static void SetOrder(object order)
{
    Order ord = GetOrder(order);
    Console.WriteLine(ord.name +","+ord.price+","+ord.orderid);        
}
public static Order GetOrder(object order)
{
    Order ord = new Order();
    Dictionary<string,object> tmp = (Dictionary<string,object>) order;
    object name = null;
    object price = null;
    object orderid = null;
    tmp.TryGetValue("name", out name);
    tmp.TryGetValue("price", out price);
    tmp.TryGetValue("orderid", out orderid);
    ord.name = name.ToString();
    ord.price = (int)price;
    ord.orderid = (int) orderid;
    return ord;
}

My code isn't that beautiful but I hope you get the meaning of it.

Comments

1

I recently went through this very issue with a complexe JSON object I wanted to deserilize in my controller. The only difference is I was using the .toJSON plugin on the client instead of .stringify.

The easy answer:

public static bool MakeReservation(string orderJSON)
{
    var serializer = new JavaScriptSerializer();
    var order = serializer.Deserialize<Order>(orderJSON);
}

Now, as a longer term solution we created a custom ActionFilterAttribute to handle these cases. It detects the JSON parameters and handles deserilizing the object and mapping to the action. You may want to look into doing the same.

Comments

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.