你可以使用 asp.net mvc Json() 将 C# 字典转换为 Javascript 关联数组吗
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3645939/
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
Can you convert C# dictionary to Javascript associative array using asp.net mvc Json()
提问by leora
I recently asked this question, but after some of the responses and some research, i wanted to change what i was actually asking.
我最近问了这个问题,但经过一些回应和一些研究,我想改变我实际问的问题。
i have seen a number of blog posts about sending associative arrays from javascript to C#controller action but i want the opposite. I want to return json to a client as a dictionary (from my research the javascript equivalent of dictionary is an associative array).
我看过许多关于将关联数组从 javascript 发送到 C#控制器操作的博客文章,但我想要相反的内容。我想将 json 作为字典返回给客户端(根据我的研究,字典的 javascript 等价物是一个关联数组)。
when i take a regular dictionary in c sharp and call Json() on it and try to return it to javascript, it just blows up and i am unable to even put a breakpoint on the javascript side. For example:
当我在 c 中使用常规字典并在其上调用 Json() 并尝试将其返回给 javascript 时,它只是爆炸了,我什至无法在 javascript 端放置断点。例如:
C# Code:
C# 代码:
Dictionary<string, List<CalendarEvent>> dict = events.GroupBy(r => r.Date.ToString("MMM dd, yyyy")).ToDictionary(group => group.Key, group => group.ToList());
return Json(new
{
Dict = dict
}
});
Javascript Code:
Javascript代码:
$.post('/MyController/Refresh', function (data) {
var calendarDictionary = data.Dict;
}, "json");
采纳答案by Darin Dimitrov
You probably could have been a little more specific about the it just blows uppart but here's an example that works fine for me:
你可能对它只是爆炸部分更具体一点,但这里有一个对我来说很好用的例子:
Model:
模型:
public class CalendarEvent
{
public string Name { get; set; }
public DateTime Date { get; set; }
public int Id { get; set; }
}
Controller:
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Refresh()
{
var model = new[]
{
new CalendarEvent
{
Id = 1,
Name = "event 1",
Date = DateTime.Now
},
new CalendarEvent
{
Id = 2,
Name = "event 2",
Date = DateTime.Now
},
new CalendarEvent
{
Id = 3,
Name = "event 3",
Date = DateTime.Now.AddDays(2)
},
}
.ToList()
.ConvertAll(a => new
{
a.Name,
a.Id,
Date = a.Date.ToString("MMM dd, yyyy"),
})
.GroupBy(r => r.Date)
.ToDictionary(
group => group.Key,
group => group.Select(x => new { x.Name, x.Id })
);
return Json(new { Dict = model });
}
}
View:
看法:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JSON Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$.post('/home/refresh', function(data) {
// TODO : manipulate the data.Dict here
}, 'json');
});
</script>
</head>
<body>
</body>
</html>
Returned JSON:
返回的 JSON:
{ "Dict": { "Sep 05, 2010": [ { "Name": "event 1", "Id": 1 },
{ "Name": "event 2", "Id": 2 } ],
"Sep 07, 2010": [ { "Name": "event 3", "Id": 3 } ] } }
回答by James Sumners
回答by Davy Meers
In json you have two main structures: an "array", this is a list of element, and an "object", a group of key-value pairs.
在 json 中,您有两个主要结构:一个“数组”,这是一个元素列表,一个“对象”,一组键值对。
So for what you want to achieve the json method has to return a json object (debug the server side to see what is actually send to the client).
所以对于你想要实现的 json 方法必须返回一个 json 对象(调试服务器端以查看实际发送给客户端的内容)。
In javascript the json object will be directly mapped to a javascript object, and in javascript objects are also associative arrays
在javascript中json对象会直接映射到javascript对象上,在javascript中对象也是关联数组
So to summarize:
所以总结一下:
Make sure the server returns a json object, then you can use it as some kind of dictionary in javascript.
确保服务器返回一个 json 对象,然后您可以将其用作 javascript 中的某种字典。
回答by ScottE
Your code isn't valid - perhaps a typo?
您的代码无效 - 也许是错字?
$.post('/MyController/Refresh', function (data) {
var calendarDictionary = data.Dict;
}, "json");
Also, I've seen cases where a method needs the data param, even if it's empty {}.
另外,我见过方法需要数据参数的情况,即使它是空的 {}。
Finally, the json should come back inside data.d - use firebug to console.log the response.
最后,json 应该返回到 data.d 中 - 使用 firebug 来 console.log 响应。

