Accessing MVC3 Model Properties from Javascript in a View

I am trying to create google diagram in mvc application.

Here is a javascript snippet of google chart

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 essentially replaces the line data.addRows above with a for loop repeating through the elements of my model. Of course, I can accurately iterate through the appearance of the tag, for example:

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

I can not find a solution to iterate through my INSIDE model tag. Any ideas?

+4
source share
1 answer

Assuming you have a view model:

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

in which you save some values ​​and go 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 can 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 displayed 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 don't have to worry about having values ​​that contain single or double quotes, which could potentially break your javascript, because you used the JSON serializer instead of manually creating it.

+7
source

Source: https://habr.com/ru/post/1393000/


All Articles