chart.js ajax,javascript - How to build ajax-chartjs line-chart in asp mvc application? - Stack Over...

夏侯华彩
2023-12-01

I have following code in my view:

@Styles.Render("~/Content/newcss")

@Scripts.Render("~/bundles/chartscripts")

@Scripts.Render("~/scripts/jquery-1.10.2.js")

@Scripts.Render("~/scripts/jquery.unobtrusive-ajax.js")

$.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 !");}});

...

And in controller:

[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);

}

I tried to build line chart with chartjs, and without Ajax I have done it, but I want to my chart rebuild automatically without page refreshing and without any actions on page (triggers for Ajax like clicking buttons etc) when I get a new items in the database. With this code I always go to the error block.

 类似资料: