我不知道如何用我的代码返回 JSON 数据。
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);
}
});
});
Default.aspx.cs 的 C#
[WebMethod]
public static string GetProducts()
{
var products = context.GetProducts().ToList();
return What do I have to return ????
}
提前致谢!
最佳答案
你不远;你需要做这样的事情:
[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;
}
您可以进一步减少这段代码,但为了清楚起见,我保留了它。事实上,你甚至可以这样写:
return context.GetProducts().ToList();
这将返回一个 json 字符串。我更喜欢更明确,因为我使用自定义转换器。还有 Json.net,但框架的 JavaScriptSerializer
开箱即用。
关于c# - 如何使用 ASP.NET 和 jQuery 返回 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18244696/