Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return JSON with ASP.NET & jQuery

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!

like image 407
Friend Avatar asked Aug 15 '13 00:08

Friend


People also ask

How do I return a JSON response in C#?

ContentType = "application/json; charset=utf-8"; Response. Write(myObjectJson ); Response. End(); So you return a json object serialized with all attributes of MyCustomObject.

How do I return JSON in Web API net core?

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 .


2 Answers

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.

like image 61
frenchie Avatar answered Sep 19 '22 18:09

frenchie


Just return object: it will be parser to JSON.

public Object Get(string id) {     return new { id = 1234 }; } 
like image 32
TimChang Avatar answered Sep 17 '22 18:09

TimChang