Access MVC3 Model properties from Javascript in the View

前端 未结 1 1010
半阙折子戏
半阙折子戏 2021-01-06 10:42

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.vis         


        
1条回答
  •  不要未来只要你来
    2021-01-06 11:17

    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
    
    

    which will be rendered in the final markup as:

    
    

    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.

    0 讨论(0)
提交回复
热议问题