如何在asp mvc应用程序中构建ajax-chartjs折线图?

时间:2018-04-02 17:00:55

标签: javascript c# asp.net-mvc charts

我在视图中有以下代码:

@Styles.Render("~/Content/newcss")
@Scripts.Render("~/bundles/chartscripts")
@Scripts.Render("~/scripts/jquery-1.10.2.js")
@Scripts.Render("~/scripts/jquery.unobtrusive-ajax.js")
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.bundle.min.js">
</script>

<script>
$.ajax({
    type: "post",
    url: "/GraphicsController/AjaxChart",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function () {
    var ctx1 = document.getElementById("Linecanvas").getContext("2d");
    window.myBar = new Chart(ctx1,
        {   type: 'line',
            data: {
                labels: [@Html.Raw(Json.Encode(@ViewBag.ContentIds))],
                datasets: [{
                        label: "Common Responses",
                        backgroundColor: "rgba(75,192,192,0.4)",
                        borderWidth: 2,
                        data: [@Html.Raw(Json.Encode(@ViewBag.ContentIds))]
                    },{
                        label: "Delayed Responses",
                        backgroundColor: "rgba(75,192,192,0.4)",
                        borderWidth: 2,
                        data: 
[@Html.Raw(Json.Encode(@ViewBag.DelayedResponseTimes))]
                    }]},
            options:{title:
                    {display: true,
                        text: "Graphic"},
                    responsive: true,
                    maintainAspectRatio: true
                }});},
    error: function OnErrorCall_(repo) {alert("Woops something went wrong, 
pls try later !");}});
</script>  
</head>
<body>
<div id="wrapper">
    <div id="div-chart">
        <canvas id="Linecanvas"></canvas>
    </div>
    ...
<body>

在控制器中:

[HttpPost]
public ActionResult AjaxChart() {
  IEnumerable < DBContent > contents = db.DBContents;

  var delayedResponses = contents.Where(r => r.DelayedResponseTime != 0).Select(x => x.DelayedResponseTime);
  var commonResponses = contents.Where(r => r.CommonResponseTime != 0).Select(x => x.CommonResponseTime);
  ViewBag.DelayedResponseTimes = delayedResponses.ToList();
  ViewBag.CommonResponseTimes = commonResponses.ToList();

  var ContentIds = new List < int > () {};
  for (var i = 1; i <= delayedResponses.Count(); i++) {
    ContentIds.Add(i);
  }
  ViewBag.ContentIds = ContentIds;
  return Json(delayedResponses.ToList(), JsonRequestBehavior.AllowGet);
}

我尝试使用chartjs构建折线图,没有Ajax我已经完成了,但我希望我的图表能够自动重建而不会刷新页面而且页面上没有任何操作(Ajax的触发器,例如单击按钮等)当我得到一个数据库中的新项目。使用此代码,我总是转到error块。

2 个答案:

答案 0 :(得分:2)

谢谢...它成功为我工作。但是几乎不需要更改:

public ActionResult AjaxChart()

收件人:

public JsonResult AjaxChart()

答案 1 :(得分:1)

您不能将ViewBag与Ajax一起使用,您只能返回一个结果对象。将所有返回的对象组合为一个父对象的属性:

[HttpGet]
public ActionResult AjaxChart() {
    IEnumerable<DBContent> contents = db.DBContents;

    var delayedResponses = contents.Where(r => r.DelayedResponseTime != 0)
                                   .Select(x => x.DelayedResponseTime);
    var commonResponses = contents.Where(r => r.CommonResponseTime != 0)
                                  .Select(x => x.CommonResponseTime);

    var ContentIds = new List<int>();
    for (var i = 1; i <= delayedResponses.Count(); i++) {
        ContentIds.Add(i);
    }

    var result = new {
        DelayedResponseTimes = delayedResponses.ToList(),
        CommonResponseTimes = commonResponses.ToList(),
        ContentIds = ContentIds
    };
    return Json(result, JsonRequestBehavior.AllowGet);
}

现在,在你的jQuery中,你需要获取数据(你没有这样做)。改变这一行:

success: function () {

为:

success: function (result) {

然后您需要使用ViewBag将所有这些行更改为使用result参数:

success: function(result) {
  var ctx1 = document.getElementById("Linecanvas").getContext("2d");
  window.myBar = new Chart(ctx1, {
    type: 'line',
    data: {
      labels: result.ContentIds,
      datasets: [{
        label: "Common Responses",
        backgroundColor: "rgba(75,192,192,0.4)",
        borderWidth: 2,
        data: result.CommonResponseTimes
      }, {
        label: "Delayed Responses",
        backgroundColor: "rgba(75,192,192,0.4)",
        borderWidth: 2,
        data: result.DelayedResponseTimes
      }]
    },
    options: {
      title: {
        display: true,
        text: "Graphic"
      },
      responsive: true,
      maintainAspectRatio: true
    }
  });
},

最后,在您的方法的URL中,您必须使用没有后缀的控制器的名称,因此更改此行:

url: "/GraphicsController/AjaxChart",

为:

url: "/Graphics/AjaxChart",

最好让ASP为您生成网址,以防您更改路由或重命名方法:

url: @Url.Action(nameof(GraphicsController.AjaxChart), "Graphics"),