从MVC控制器获取JavaScript数据

从MVC控制器获取JavaScript数据,javascript,asp.net-mvc,Javascript,Asp.net Mvc,我使用谷歌图表中的时间线选项来显示一些物品的可用性 链接: 它显示如下内容 使用此代码: google.setOnLoadCallback(drawChart); function drawChart() { var container = document.getElementById('example3.1'); var chart = new google.visualization.Timeline(container); var dataTable = new goo

我使用谷歌图表中的时间线选项来显示一些物品的可用性

链接:

它显示如下内容

使用此代码:

google.setOnLoadCallback(drawChart);
function drawChart() {

  var container = document.getElementById('example3.1');
  var chart = new google.visualization.Timeline(container);

  var dataTable = new google.visualization.DataTable();
  dataTable.addColumn({ type: 'string', id: 'Position' });
  dataTable.addColumn({ type: 'string', id: 'Name' });
  dataTable.addColumn({ type: 'date', id: 'Start' });
  dataTable.addColumn({ type: 'date', id: 'End' });
  dataTable.addRows([
    [ 'President',          'George Washington', new Date(1789, 3, 29), new Date(1797, 2, 3)],
    [ 'President',          'John Adams',        new Date(1797, 2, 3),  new Date(1801, 2, 3)],
    [ 'President',          'Thomas Jefferson',  new Date(1801, 2, 3),  new Date(1809, 2, 3)],
    [ 'Vice President',     'John Adams',        new Date(1789, 3, 20), new Date(1797, 2, 3)],
    [ 'Vice President',     'Thomas Jefferson',  new Date(1797, 2, 3),  new Date(1801, 2, 3)],
    [ 'Vice President',     'Aaron Burr',        new Date(1801, 2, 3),  new Date(1805, 2, 3)],
    [ 'Vice President',     'George Clinton',    new Date(1805, 2, 3),  new Date(1812, 3, 19)],
    [ 'Secretary of State', 'John Jay',          new Date(1789, 8, 25), new Date(1790, 2, 21)],
    [ 'Secretary of State', 'Thomas Jefferson',  new Date(1790, 2, 21), new Date(1793, 11, 30)],
    [ 'Secretary of State', 'Edmund Randolph',   new Date(1794, 0, 1),  new Date(1795, 7, 19)],
    [ 'Secretary of State', 'Timothy Pickering', new Date(1795, 7, 19), new Date(1800, 4, 11)],
    [ 'Secretary of State', 'Charles Lee',       new Date(1800, 4, 12), new Date(1800, 5, 4)],
    [ 'Secretary of State', 'John Marshall',     new Date(1800, 5, 12), new Date(1801, 2, 3)],
    [ 'Secretary of State', 'Levi Lincoln',      new Date(1801, 2, 4),  new Date(1801, 4, 0)],
    [ 'Secretary of State', 'James Madison',     new Date(1801, 4, 1),  new Date(1809, 2, 2)]]);

  chart.draw(dataTable);
}

我希望列的名称(dataTable.addColumn)的数量可变,以来自MVC控制器。有什么方法可以做到这一点吗?

是的,只要此脚本在视图中,而不是在JS文件中,您就可以在中插入变量,如:

dataTable.addColumn({ type: 'string', id: '@Model.FirstColumnName' });

MVC允许你做很多注入脚本的事情;记住,这是服务器端代码被呈现到客户端标记。你只需要确保它被正确渲染。在我的视图中,我甚至有将模型转换为JSON对象的实用程序,没有问题。

您可以实现一个MVC控制器方法,该方法返回一个JSON对象,该对象具有
类型
id
属性,并执行ajax调用来检索它们

$.getJSON( "/Columns", function( data ) {
    $.each( data, function( key, val ) {
      //use dataTable.addColumn to add columns
    });
});

您想添加n个列?如果我们想使用不引人注目的JavaScript怎么办?除了使用ajax调用还有什么办法吗?我的方法没有使用ajax,而是在客户端标记中使用服务器端渲染。我知道,我的意思是将数据传递到单独的.js文件。哦,好吧,不一定是ajax,但它增加了复杂性。您可以使用模型中的配置构建一个JSON“configuration”对象,并将该JSON对象传递给JS文件中的方法,然后该方法用于提供列。