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:

publicclassValueObject
{
    publicstring Value { get; set; }
}

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

[System.Web.Services.WebMethod]
publicstaticstringGetCurrentTime(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

publicclassName
    {
        publicstringvalue { get; set; }
    }

    publicclassRootObject
    {
        public List<Name> name { get; set; }
    }

And change your page method signature as below

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

Post a Comment for "Json, Ajax, And Asp.net"