Skip to content Skip to sidebar Skip to footer

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.We

Solution 1:

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


Solution 2:

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

Post a Comment for "JSON, AJAX, And ASP.NET"