leo*_*ora 13 javascript asp.net-mvc json dictionary associative-array
我最近问过这个问题,但经过一些回应和一些研究之后,我想改变我实际要问的内容.
我已经看过很多关于从javascript到C# controller动作发送关联数组的博客文章,但我想要相反.我想将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
}
});
Run Code Online (Sandbox Code Playgroud)
Javascript代码:
$.post('/MyController/Refresh', function (data) {
var calendarDictionary = data.Dict;
}, "json");
Run Code Online (Sandbox Code Playgroud)
Dar*_*rov 11
你可能会更加具体一点,它只是爆炸部分,但这是一个适合我的例子:
模型:
public class CalendarEvent
{
public string Name { get; set; }
public DateTime Date { get; set; }
public int Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
控制器:
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 });
}
}
Run Code Online (Sandbox Code Playgroud)
视图:
<%@ 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>
Run Code Online (Sandbox Code Playgroud)
返回JSON:
{ "Dict": { "Sep 05, 2010": [ { "Name": "event 1", "Id": 1 },
{ "Name": "event 2", "Id": 2 } ],
"Sep 07, 2010": [ { "Name": "event 3", "Id": 3 } ] } }
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
18131 次 |
最近记录: |