How to return JSON with ASP.NET & jQuery

ajax, asp.net, c#, javascript, jquery

Solution

You're not far; you need to do something like this:

[WebMethod]
public static string GetProducts()
{
  // instantiate a serializer
  JavaScriptSerializer TheSerializer = new JavaScriptSerializer();

  //optional: you can create your own custom converter
  TheSerializer.RegisterConverters(new JavaScriptConverter[] {new MyCustomJson()});

  var products = context.GetProducts().ToList();   

  var TheJson = TheSerializer.Serialize(products);

  return TheJson;
}

You can reduce this code further but I left it like that for clarity. In fact, you could even write this:

return context.GetProducts().ToList();

and this would return a json string. I prefer to be more explicit because I use custom converters. There's also Json.net but the framework's `JavaScriptSerializer` works just fine out of the box.

Problem

I cannot get how I can return JSON data with my code. JS ``` $(function () { $.ajax({ type: "POST", url: "Default.aspx/GetProducts", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { // How to return data here like a table??? $("#Second").text(msg.d); //alert(msg.d); } }); }); ``` C# of Default.aspx.cs ``` [WebMethod] public static string GetProducts() { var products = context.GetProducts().ToList(); return What do I have to return ???? } ```

Original source

Related problems