Shane Sepac
Shane Sepac

Reputation: 826

JSON, AJAX, and ASP.NET

My client-side file has an ajax call in its jQuery which sends JSON data to a server-side WebMethod. The following code works:

WebMethod on server-side (C#)

[System.Web.Services.WebMethod]
public static string GetCurrentTime(string[] name)
{
    string str = "";
    foreach(string s in name)
    {
        str += s;
    }
    return str;
}

and the ajax call (jQuery):

        //array = ["a","b","c"]
        //data = {'name':["a","b","c"]}
        $.ajax({
            type: "POST",
            url: "schedule.aspx/GetCurrentTime",
            data: "{'name':" + JSON.stringify(array) + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response){
                alert(response.d);
            },
            complete: function () {
                alert("complete");
            }
        });

tl;dr The above code takes the JSON string and creates an array of strings in the server-side method.

How would I rewrite the above WebMethod if I change the JSON to the following? "name" no longer is an array of strings as it was in the above code, but an array of some object, so the parameter type in the WebMethod would need to be changed but I'm not sure to what.

{"name":[{"value":"val1"},{"value":"val2"}]}

This is the message and stacktrace I'm receiving on Chrome's Network tab when I execute the ajax request:

Message
:
"No parameterless constructor defined for type of 'System.String'."
StackTrace
:
"   at System.Web.Script.Serialization.ObjectConverter.ConvertDictionaryToObject(IDictionary`2 dictionary, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)
↵   at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)
↵   at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)
↵   at System.Web.Script.Serialization.ObjectConverter.AddItemToList(IList oldList, IList newList, Type elementType, JavaScriptSerializer serializer, Boolean throwOnError)
↵   at System.Web.Script.Serialization.ObjectConverter.ConvertListToObject(IList list, Type type, JavaScriptSerializer serializer, Boolean throwOnError, IList& convertedList)
↵   at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)
↵   at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)
↵   at System.Web.Script.Services.WebServiceMethodData.StrongTypeParameters(IDictionary`2 rawParams)
↵   at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)
↵   at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)
↵   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)"

Upvotes: 0

Views: 1376

Answers (2)

santosh singh
santosh singh

Reputation: 28642

if you want to paas {"name":[{"value":"val1"},{"value":"val2"}]} value to your web method then create a data model as shown below

 public class Name
    {
        public string value { get; set; }
    }

    public class RootObject
    {
        public List<Name> name { get; set; }
    }

And change your page method signature as below

[WebMethod]
[ScriptMethod]
public static string GetCurrentTime(RootObject list)
{
    string str = "";
    foreach (var s in list.name)
    {
        str += s.Value;
    }
    return str;
}

Upvotes: 0

nemesv
nemesv

Reputation: 139748

If you want to send in a complex object to your webmethod eg. {"value":"val1"} then you need to create a C# class with properties matching your JSON to be able to receive the data.

So in your case you need a data class, something like:

public class ValueObject
{
    public string Value { get; set; }
}

Then you need to change your webmethod to accept an array of ValueObject:

[System.Web.Services.WebMethod]
public static string GetCurrentTime(ValueObject[] name)
{
    string str = "";
    foreach (var s in name)
    {
        str += s.Value;
    }
    return str;
}

Note the property name Value has to match the property name in your JSON value

Upvotes: 2

Related Questions