你可以使用asp.net mvc Json()将C#字典转换为Javascript关联数组

前端之家收集整理的这篇文章主要介绍了你可以使用asp.net mvc Json()将C#字典转换为Javascript关联数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我最近 asked this question,但经过一些回应和一些研究,我想改变我实际要求的.

我看到了一个number of blog posts about sending associative arrays from javascript to C#控制器的动作,但我想要相反.我想把json作为一个字典返回给客户端(从我的研究中,javascript相当于dictionary是一个关联数组).

当我在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");

解决方法

你可能会有一点更具体的,它只是吹起了部分,但这里是一个很好的例子,对我来说:

模型:

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",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相关文章