简体   繁体   中英

Access MVC3 Model properties from Javascript in the View

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

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]
    ]);

}

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);
    }
}

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM