Friday, April 12, 2013

How to return JSON string from ASP.NET WebMethod

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

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

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

Method 2 - Uses ScriptMethod with the WebMethod


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

No comments:
Write comments
Recommended Posts × +