Monday, January 13, 2014

Return Json Data to Ajax Success call in asp.net

In asp.net, there are many ways to return Json data to your Ajax Success Method. One of them is as follows:

Create a static class as ExtensionClass:

using System.Web.Script.Serialization;
namespace Extensions
{
        public static string ToJson(this object obj)
        {
            var serializer = new JavaScriptSerializer();
            return serializer.Serialize(obj);
        }

        public static string ToJson(this object obj, int recursionDepth)
        {
            var serializer = new JavaScriptSerializer {RecursionLimit = recursionDepth};
            return serializer.Serialize(obj);
        }
}

Make sure you use the namespace System.Web.Script.Serialization to use the JavaScriptSerializer() as above.

Now, to make use of the above statement in return web method. Use the following:

Class having properties:

public class JsonData
{
       public string Id{get;set;}
       public string Name{get;set;}
       public string Status{get;set;}
}

Test.aspx.cs Web Page:
[System.Web.Services.WebMethod]
public static string ShowInfo()
{
     //Your Set of Statements
    var jsonData = new JsonData
                                               {
                                                   Id = "1",
                                                   Name = "Amit Jain",
                                                   Status = "Ok"
                                               };
    return jsonData.ToJson();
}


Jquery Ajax Call:
<script type='text/javascript'>
function testMethod()
{
     $.ajax({
                    type: "POST",
                    contentType: "application/json",
                    url: "Test.aspx/ShowInfo",
                    dataType: "json",
                    data: "",
                    success:
                    function (Result) {                              //Success Method
                        if (Result != '') {
                            var jSonData = JSON.parse(Result.d);
                             alert(jSonData.Name);
                        }
                    },
                    error:
                    function (XMLHttpRequest, textStatus, errorThrown) {
                    }
                });
}
</script>


I hope this helps.

Thanks
Amit Jain

No comments:

Post a Comment