More
Image
How to return JSON string from ASP.NET WebMethod
By JC.Adinarayana Reddy On 20 Dec 2016
Categories: web services
  1. Recently i worked with making some ajax calls to the server. There we need to get the response from the server as a JSON string. I have used two ways of returning a JSON string from a ASP.NET WebMethod.

    Method 1 - Uses the JavaScriptSerializer

    [WebMethod]
    public string GetLankanList()
    {
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    List lankanList = new List();
    string[] names = { "chamara", "janaka", "asanka" };

    for (int i = 0; i < names.Length; i++)
    {
    Lankans srilankans = new Lankans();
    srilankans.Name = names[i];
    lankanList.Add(srilankans);
    }
    string jsonString = serializer.Serialize(lankanList);
    return jsonString;
    }

    Method 2 - Uses ScriptMethod with the WebMethod

    [WebMethod]

    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public string getData() 
     try 
     { 
     string name="chamara";
    return name; 
     } 
     catch (Exception ex) { 
     throw ex; 
     } 
     }

 


Comments
Message :
Comments
JC.Adinarayana Reddy
.net
.net