如何使用ASP.NET和jQuery返回JSON

Dev*_*per 37 javascript c# asp.net ajax jquery

我无法得到如何使用我的代码返回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);
        }
    }); 
});
Run Code Online (Sandbox Code Playgroud)

Default.aspx.cs的C#

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

提前致谢!

fre*_*hie 38

你不远; 你需要做这样的事情:

[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;
}
Run Code Online (Sandbox Code Playgroud)

您可以进一步减少此代码,但为了清晰起见,我将其保留了下来.事实上,你甚至可以这样写:

return context.GetProducts().ToList();
Run Code Online (Sandbox Code Playgroud)

这将返回一个json字符串.我更喜欢更明确,因为我使用自定义转换器.还有Json.net,但框架的JavaScriptSerializer开箱即用.

  • 你也可以使用`JavaScriptSerializer`` [ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)]在`static method`之上添加它. (5认同)

Tim*_*ang 13

只返回对象:它将解析为JSON.

public Object Get(string id)
{
    return new { id = 1234 };
}
Run Code Online (Sandbox Code Playgroud)


小智 5

这个结构对我有用 - 我在一个小任务管理应用程序中使用它.

控制器:

public JsonResult taskCount(string fDate)
{
  // do some stuff based on the date

  // totalTasks is a count of the things I need to do today
  // tasksDone is a count of the tasks I actually did
  // pcDone is the percentage of tasks done

  return Json(new {
    totalTasks = totalTasks,
    tasksDone = tasksDone,
    percentDone = pcDone
  });
}
Run Code Online (Sandbox Code Playgroud)

在AJAX调用中,我访问如下数据:

.done(function (data) {
  // data.totalTasks
  // data.tasksDone
  // data.percentDone
});
Run Code Online (Sandbox Code Playgroud)