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

发布于 2024-09-17 18:14:42 字数 985 浏览 5 评论 0原文

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

我看到了 关于将关联数组从 javascript 发送到 C# 控制器操作的博客文章数量,但我想要相反的结果。我想将 json 作为字典返回给客户端(根据我的研究,字典的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

残疾 2024-09-24 18:14:42

您可能可以对它只是爆炸部分有更具体的了解,但这里有一个对我来说效果很好的示例:

模型:

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 } ] } }

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:

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:

{ "Dict": { "Sep 05, 2010": [ { "Name": "event 1", "Id": 1 },
                              { "Name": "event 2", "Id": 2 } ],
            "Sep 07, 2010": [ { "Name": "event 3", "Id": 3 } ] } }
萌︼了一个春 2024-09-24 18:14:42

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

画骨成沙 2024-09-24 18:14:42

您可能想查看 Json.NET 库。它使得创建 .Net 对象的 JSON 表示变得非常简单。

You might want to look at the Json.NET library. It makes creating JSON representations of .Net objects very simple.

错爱 2024-09-24 18:14:42

您的代码无效 - 也许是拼写错误?

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

           var calendarDictionary = data.Dict;

    }, "json");

另外,我见过方法需要数据参数的情况,即使它是空的 {}。

最后,json 应该返回到 data.d 中 - 使用 firebug 来 console.log 响应。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文