0

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)"

2 Answers 2

2

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

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

1 Comment

Worked for me! Thanks. I wish there was better documentation on my problem.
0

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;
}

5 Comments

what was the issue
The problem ended up being that the parameter in the ajax call is NOT sent to the WebMethod on the server side as a string. The JSON string in the data field of the ajax call is actually converted to the object type specified by the WebMethod's signature. That being said, my problem was that the data was not being passed into the WebMethod as a string, but a different object type.
your solution was extremely close. But ultimately the answer that I marked as the solution worked.
I tested my code with your data and it was working fine
I copied your code exactly as you posted it and it didn't work. I copied the code from the working solution and it worked.

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.