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 ???? }   Thanks in advance!
ContentType = "application/json; charset=utf-8"; Response. Write(myObjectJson ); Response. End(); So you return a json object serialized with all attributes of MyCustomObject.
To return data in a specific format from a controller that inherits from the Controller base class, use the built-in helper method Json to return JSON and Content for plain text. Your action method should return either the specific result type (for instance, JsonResult ) or IActionResult .
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.
Just return object: it will be parser to JSON.
public Object Get(string id) {     return new { id = 1234 }; } 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With