Search code examples
javascriptasp.netjsonajaxwebmethod

Passing complex JSON to a WebMethod


I'm trying to pass an JSON that has the following structure:

{"var":"{"var1:"val1","var2:"val2",...,"varN:"valN"}"}

My JS function executing the following POST function:

$.ajax({
    type: "POST",
    url: "MyWebApp.aspx/Foo",
    data:  {"json":"{"var1:"val1","var2:"val2",...,"varN:"valN"}"},
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        alert("2D JSON Test is done")
    }
});

I want to know how to define the WebMethod function prototype to receive the JSONs like this?

[WebMethod]
public static void Foo(var json)

or

[WebMethod]
public static void Foo(string json)

or

[WebMethod]
public static void Foo(string[] json)

or

[WebMethod]
public static void Foo(List<string> json)

Solution

  • Refer the link:sending JSON object successfully to asp.net WebMethod, using jQuery

    [WebMethod]
            public static void Foo(object items)
            {
                //break point here
                List<object> lstItems = new JavaScriptSerializer().ConvertToType<List<object>>(items);
            }