我正在ASP.NET MVC4开发系统。我在JavaScript上写了一个代码,并且页面启动时执行,以显示有关某些学生表现的图表。
该图的代码为以下
<script>
window.onload = function () {
var r = Raphael("holder"),
txtattr = { font: "20px sans-serif" };
var lines = r.linechart(30, 30, 600, 440,<%= Json.Encode(ViewBag.dates) %>,<%= Json.Encode(ViewBag.Grades)%>, {axisxstep : 6,nostroke: false, axis: "0 0 1 1", symbol: "circle", smooth: false }).hoverColumn(function () {
this.tags = r.set();
for (var i = 0, ii = this.y.length; i < ii; i++) {
this.tags.push(r.tag(this.x, this.y[i], Number(this.values[i]).toFixed(5), 160, 10).insertBefore(this).attr([{ fill: "#fff" }, { fill: this.symbols[i].attr("fill") }]));
}
});
</script>
该图的数据来自控制器DisplayGraph
的功能。控制器的代码如下所示。
public ActionResult DisplayGraph(String InputStudent = "IP11")
{
var query = (from b in db.gradesPerStudent
where b.Student.Equals(InputStudent)
orderby b.Date
select b);
ViewBag.ChartEmpty = "No";
if (query.ToList().Count == 0)
{
ViewBag.ChartEmpty = "Yes";
ViewBag.Title = "No results for Student " + InputStudent;
ViewBag.dates = null;
ViewBag.grades = null;
DateTime aminDate = new DateTime();
ViewBag.minDate = aminDate.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds;
return View();
}
DateTime minDate = query.Min(y => y.Date);
DateTime maxDate = query.Max(y => y.Date);
var dates = query.Select(x => EntityFunctions.DiffDays(query.Min(y => y.Date), x.Date));
var grades = query.Select(x => x.grades);
var datestable = dates.ToArray();
var gradestable = grades.ToArray();
List<int?> dateslist = new List<int?>();
List<double> gradeslist = new List<double>();
double result = dates.Count() * 1.0 / 70.0;
int pointStep = (int)Math.Ceiling(result);
for (int i = 0; i < dates.Count(); i = i + pointStep)
{
dateslist.Add(datestable.ElementAt(i));
gradeslist.Add(gradestable.ElementAt(i));
}
ViewBag.dates = dateslist;
ViewBag.grades = gradeslist;
ViewBag.minDate = minDate.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds;
return View(query.ToList());
}
现在,当学生在学校新的时候,我不想显示图表,而是一条消息,说学生是新的,尚无统计数据。
所以我的问题是。当应该执行JavaScript并且未能执行时,我如何从控制器中说?
非常感谢
当应执行JavaScript时,我的控制器我怎么说 什么时候不?
通过视图模型。视图模型应包含呈现视图所需的所有信息,并且视图应包含您的脚本(或指向其链接)。
尝试使用ViewBag
最小化,并更喜欢强大的模型。
模型
public class MyViewModel {
public bool ShowGraph { get; set; }
public List<object> Data { get; set; }
public List<int?> Dates { get; set; }
public List<double> Grades { get; set; }
}
控制器
public ActionResult Index(){
var model = new MyViewModel();
model.ShowGraph = !IsStudentNew();
// set your other properties here, instead of using the ViewBag
return View( model );
}
查看
@model MyViewModel
@if( Model.ShowGraph ){
<script>
// javascript to render graph goes here
</script>
}else{
<div>No statistics yet.</div>
}
我只有您的模型的 GraphText
属性。在图表的顶部显示它。如果有统计信息,请将此属性空白。如果没有..给它一个值:
public class YourModel {
public IList<Statistic> StudentStatistics { get; set; }
public string GraphText {
get {
return StudentStatistics.Any() ? "" : "No statistics yet";
}
}
}
然后在您的视图中,只需在图表顶部渲染GraphText
属性。