在MVC中,我想从控制器创建带有JSON的ViewData,并在视图中使用它来获取谷歌图表

时间:2016-08-04 13:13:20

标签: c# asp.net-mvc json.net

在控制器的下面,我创建列表并将其转换为JSON序列化格式

List<Models.EmployeeCounts> coverageOffersCount = new List<Models.EmployeeCounts>();
        coverageOffersCount.Add(new EmployeeCounts() { Description = "Not Offered", Count = 10});
        coverageOffersCount.Add(new EmployeeCounts() { Description = "Waived", Count = 20});
        coverageOffersCount.Add(new EmployeeCounts() { Description = "Enrolled", Count = 30});

 JavaScriptSerializer serializer = new JavaScriptSerializer();
 ViewData["JsonCoverageCounts"] = serializer.Serialize(coverageOffersCount);

现在,我想将这个创建的ViewData用于View

1 个答案:

答案 0 :(得分:1)

如果您想要将其读取并存储到javascript变量,则可以执行此操作

var itemArray = @Html.Raw(ViewData["JsonCoverageCounts"]);

//Let's print it in console
console.log(itemArray);

itemArray将是一个对象数组,每个对象都有CountDescription属性