C# 如何使用 ASP.NET 和 jQuery 返回 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18244696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return JSON with ASP.NET & jQuery
提问by Developer
I cannot get how I can return JSON data with my code.
我不知道如何用我的代码返回 JSON 数据。
JS
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
Default.aspx.cs 的 C#
[WebMethod]
public static string GetProducts()
{
var products = context.GetProducts().ToList();
return What do I have to return ????
}
Thanks in advance!
提前致谢!
采纳答案by frenchie
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.
这将返回一个 json 字符串。我更喜欢更明确,因为我使用自定义转换器。还有 Json.net,但该框架JavaScriptSerializer
开箱即用。
回答by Steve Mc
Asp.net is pretty good at automatically converting .net objects to json. Your List object if returned in your webmethod should return a json/javascript array. What I mean by this is that you shouldn't change the return type to string (because that's what you think the client is expecting) when returning data from a method. If you return a .net array from a webmethod a javaScript array will be returned to the client. It doesn't actually work too well for more complicated objects, but for simple array data its fine.
Asp.net 非常擅长将 .net 对象自动转换为 json。如果在您的 webmethod 中返回,您的 List 对象应该返回一个 json/javascript 数组。我的意思是,从方法返回数据时,不应将返回类型更改为字符串(因为这是您认为客户端所期望的)。如果您从 webmethod 返回一个 .net 数组,一个 javaScript 数组将返回给客户端。对于更复杂的对象,它实际上并不能很好地工作,但对于简单的数组数据它很好。
Of course, it's then up to you to do what you need to do on the client side.
当然,然后由您来做您需要在客户端做的事情。
I would be thinking something like this:
我会想这样的事情:
[WebMethod]
public static List GetProducts()
{
var products = context.GetProducts().ToList();
return products;
}
There shouldn't really be any need to initialise any custom converters unless your data is more complicated than simple row/col data
除非您的数据比简单的行/列数据更复杂,否则真的不需要初始化任何自定义转换器
回答by Loubna H
Try to use this , it works perfectly for me
尝试使用它,它非常适合我
//
varb = new List<object>();
// Example
varb.Add(new[] { float.Parse(GridView1.Rows[1].Cells[2].Text )});
// JSON + Serializ
public string Json()
{
return (new JavaScriptSerializer()).Serialize(varb);
}
// Jquery SIDE
var datasets = {
"Products": {
label: "Products",
data: <%= getJson() %>
}
回答by AnotherOther
This structure works for me - I used it in a small tasks management application.
这种结构对我有用 - 我在一个小型任务管理应用程序中使用了它。
The controller:
控制器:
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
});
}
In the AJAX call I access the data like this:
在 AJAX 调用中,我像这样访问数据:
.done(function (data) {
// data.totalTasks
// data.tasksDone
// data.percentDone
});
回答by TimChang
Just return object: it will be parser to JSON.
只需返回对象:它将被解析为 JSON。
public Object Get(string id)
{
return new { id = 1234 };
}