2016-01-22 214 views
1

我自己唱asp.net mvc 4並在視圖中放置了一個圖表。我想從controller加載它的系列。我怎樣才能做到這一點 ?請任何人都可以用一段代碼來解釋它。將圖表系列從控制器傳遞到剃刀視圖

索引視圖

@{ 
var myChart = new Chart(width: 600, height: 400) 
    .AddTitle("Chart Title") 
    .AddSeries(
     name: "Views", 
     xValue: new[] { "Monday", "Tuesday", "Wendesday", "Thursday", "Friday" }, 
     yValues: new[] { "2", "6", "4", "5", "3" }) 
    .AddSeries(
     name: "Downloads", 
     xValue: new[] { "Monday", "Tuesday", "Wendesday", "Thursday", "Friday" }, 
     yValues: new[] { "1", "2", "3", "4", "5" }) 

     .Write(); 
} 

控制器

public ActionResult Index() 
    { 
     return View(); 
    } 

回答

1

這是絕對可能的。我們首先創建一個新的視圖模型來表示圖表數據。

public class ChartSeriesData 
{ 
    public string[] XValues { set; get; } 
    public string[] YValues { set; get; } 
    public string Name { set; get; } 
} 

public class MyChartData 
{ 
    public List<ChartSeriesData> Series { set; get; } 
    public string Name { set; get; } 
} 

而在你的操作方法,創建一個對象,如果MyChartData類,設置不同的屬性值,並將其發送給視圖。

public ActionResult MyChart() 
{ 
    var vm= new MyChartData { Name = "MyChartTitle",Series = new List<ChartSeriesData>()}; 
    vm.Series.Add(new ChartSeriesData 
    { 
     Name = "View", 
     XValues = new[] { "Monday", "Tuesday", "Wendesday", "Thursday", "Friday" }, 
     YValues = new[] { "2", "6", "4", "5", "3" }} 
    ); 

    vm.Series.Add(new ChartSeriesData 
    { 
     Name = "Downloads", 
     XValues = new[] { "Monday", "Tuesday", "Wendesday", "Thursday", "Friday" }, 
     YValues = new[] { "1", "2", "6", "5", "3" } 
    }); 
    return View(vm); 
} 

現在,在您看來,這是強類型爲我們MyChartData視圖模型,我們將遍歷該系列屬性,並調用AddSeries方法。

@model ReplaceWithYourNameSpaceHere.MyChartData 
@{ 
    var myChart = new Chart(width: 600, height: 400) 
     .AddTitle(Model.Name); 

    foreach (var item in Model.Series) 
    { 
     myChart.AddSeries(name: item.Name, xValue: item.XValues, yValues: item.YValues); 
    } 

    myChart.Write(); 
} 

如果要包括在另一剃刀視圖圖表中,可以使用圖像標記,並設置src屬性值MyChart操作方法。

<img src="@Url.Action("MyChart","Home")" alt="Some alt text" /> 

假設MyChart動作方法存在於HomeController

相關問題