Monday, May 20, 2024
Homepage · c#
 Popular · Latest · Hot · Upcoming
-1
rated 0 times [  4] [ 5]  / answers: 1 / hits: 134717  / 11 Years ago, thu, august 15, 2013, 12:00:00

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 ????
}

More From » c#

 Answers
6

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.


[#76351] Tuesday, August 13, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryder

Total Points: 473
Total Questions: 110
Total Answers: 91

Location: Northern Ireland
Member since Mon, Nov 14, 2022
2 Years ago
;