我是你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();
}
答案 0 :(得分: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; }
}
在Action方法中,如果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
视图模型中强类型的视图中,我们将遍历Series属性并调用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
操作方法。