如何返回JSON与ASP.NET和放大器; jQuery的 [英] How to return JSON with ASP.NET & jQuery

查看:108
本文介绍了如何返回JSON与ASP.NET和放大器; jQuery的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能让我怎么可以返回JSON数据与我的code。

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#Default.aspx.cs的

[WebMethod]
public static string GetProducts()
{
   var products  = context.GetProducts().ToList();   
   return What do I have to return ????
}

在此先感谢!

Thanks in advance!

推荐答案

你不远;你需要做的是这样的:

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

您可以减少这种code进一步,但我把它像清晰。事实上,你甚至可以这样写:

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();

这将返回一个JSON字符串。我preFER因为我使用自定义转换器,更明确。还有Json.net但该框架的 JavaScriptSerializer 工作得很好开箱。

这篇关于如何返回JSON与ASP.NET和放大器; jQuery的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆