我不知道如何用代码返回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); } }); });
C#的Default.aspx.cs
[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工作开箱即可。
JavaScriptSerializer