您可以使用 asp.net mvc Json() 将 C# 字典转换为 Javascript 关联数组吗
我最近问了这个问题,但经过一些回应和一些研究后,我想改变我实际要求的内容。
当我在 c Sharp 中使用常规字典并对其调用 Json() 并尝试将其返回到 javascript 时,它就会爆炸,我什至无法在 javascript 端放置断点。例如:
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 代码:
$.post('/MyController/Refresh', function (data) {
var calendarDictionary = data.Dict;
}, "json");
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).
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# Code:
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:
$.post('/MyController/Refresh', function (data) {
var calendarDictionary = data.Dict;
}, "json");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能可以对它只是爆炸部分有更具体的了解,但这里有一个对我来说效果很好的示例:
模型:
控制器:
视图:
返回的JSON:
You probably could have been a little more specific about the it just blows up part but here's an example that works fine for me:
Model:
Controller:
View:
Returned JSON:
在 json 中,有两个主要结构:一个“数组”,这是一个元素列表,以及一个“对象”,一组键值对。
因此,对于你想要实现的 json 方法必须返回一个 json 对象(调试服务器端以查看实际发送到客户端的内容)。
在javascript中,json对象将直接映射到javascript对象,并且在javascript中 对象也是关联数组
总结一下:
确保服务器返回一个 json 对象,然后你可以将它用作 JavaScript 中的某种字典。
In json you have two main structures: an "array", this is a list of element, and an "object", a group of key-value pairs.
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).
In javascript the json object will be directly mapped to a javascript object, and in javascript objects are also associative arrays
So to summarize:
Make sure the server returns a json object, then you can use it as some kind of dictionary in javascript.
您可能想查看 Json.NET 库。它使得创建 .Net 对象的 JSON 表示变得非常简单。
You might want to look at the Json.NET library. It makes creating JSON representations of .Net objects very simple.
您的代码无效 - 也许是拼写错误?
另外,我见过方法需要数据参数的情况,即使它是空的 {}。
最后,json 应该返回到 data.d 中 - 使用 firebug 来 console.log 响应。
Your code isn't valid - perhaps a typo?
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.