你可以使用asp.net mvc Json()将C#字典转换为Javascript关联数组 [英] Can you convert C# dictionary to Javascript associative array using asp.net mvc Json()

查看:107
本文介绍了你可以使用asp.net mvc Json()将C#字典转换为Javascript关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近问这个问题,但是经过一些回应和一些研究,我想改变我实际要求的内容。

I recently asked this question, but after some of the responses and some research, i wanted to change what i was actually asking.

我看到一个关于发送关联的博客帖子数数组从javascript到C#控制器动作,但我想要相反。我想把json作为一个字典返回给一个客户端(从我的研究中,javascript相当于字典是一个关联数组)。

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).

当我在c sharp并调用Json(),并尝试将其返回到javascript,它只是吹起来,我甚至无法在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#代码:

  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代码:

Javascript Code:

    $.post('/MyController/Refresh', function (data) {

           var calendarDictionary = data.Dict;

    }, "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:

型号:

public class CalendarEvent
{
    public string Name { get; set; }
    public DateTime Date { get; set; }
    public int Id { get; set; }
}

控制器:

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

查看:

<%@ 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>

返回JSON:

{ "Dict": { "Sep 05, 2010": [ { "Name": "event 1", "Id": 1 },
                              { "Name": "event 2", "Id": 2 } ],
            "Sep 07, 2010": [ { "Name": "event 3", "Id": 3 } ] } }

这篇关于你可以使用asp.net mvc Json()将C#字典转换为Javascript关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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