在视图访问MVC3型号从Javascript性能 [英] Access MVC3 Model properties from Javascript in the View

查看:107
本文介绍了在视图访问MVC3型号从Javascript性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图打造出一个谷歌的图表中的MVC应用程序。

I am trying to build out a google chart in an mvc app.

下面是谷歌图表一段JavaScript代码

Here is a snippet of google Chart javascript

function drawChart() {
 var data = new google.visualization.DataTable();
    data.addColumn('string', 'Task');
    data.addColumn('number', 'Hours per Day');
    data.addRows([

      ['Work',    11],
      ['Eat',      2],
      ['Commute',  2],
      ['Watch TV', 2],
      ['Sleep',    7]
    ]);

}

我想要做的基本上是替换以上for循环在我的模型的项目迭代的data.addRows线。我可以在视图迭代就好标签之外,像这样当然是:

what I would like to do is essentially replace the data.addRows line above with a for loop iterating through the items in my model. I can iterate just fine in the view outside of the tag like so of course:

 "@foreach (var item in Model) {
    <div>@Html.DisplayFor(modelItem => item.Customer.Name)</div>
  }"

我似乎无法找到解决办法,我的模型内的标签进行迭代。任何想法?

I cannot seem to find a solution to iterate through my model INSIDE a tag. Any ideas?

推荐答案

假设你有一个视图模型:

Assuming you have a view model:

public class MyViewModel
{
    public object[][] Values { get; set; }
}

在其中存储了一些价值,同时传递给视图:

in which you store some values and pass along to the view:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            Values = new[]
            {
                new object[] { "Work",     11 },
                new object[] { "Eat",      2 },
                new object[] { "Commute",  2 },
                new object[] { "Watch TV", 2 },
                new object[] { "Sleep",    7 },
            }
        };
        return View(model);
    }
}

在你看来你可以JSON EN code是:

in your view you could JSON encode it:

@model MyViewModel
<script type="text/javascript">
    function drawChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Task');
        data.addColumn('number', 'Hours per Day');
        data.addRows(@Html.Raw(Json.Encode(Model.Values)));
    }
</script>

,这将在最终的标记被渲染成

which will be rendered in the final markup as:

<script type="text/javascript">
    function drawChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Task');
        data.addColumn('number', 'Hours per Day');
        data.addRows([["Work",11],["Eat",2],["Commute",2],["Watch TV",2],["Sleep",7]]);
    }
</script>

和你不应该担心所有关于因为使用了一个JSON序列具有包含单个或双引号这有可能打破你的JavaScript值,而不是手动构建它。

And you shouldn't be worried at all about having values that contain single or double quotes which could potentially break your javascript because you have used a JSON serializer instead of manually building it.

这篇关于在视图访问MVC3型号从Javascript性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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