Highcharts, AJAX and MVC
There seems to be a lot of confusion regarding MVC, Ajax and Highcharts, so I thought I would post my approach, it is very simple and I hope this helps someone.
A simple controller returns an array of doubles from the DB for rendering data via an Ajax GET request. The chart used in this example is an irregular series chat.
[Authorize]
public class AjaxController : Controller
{
DataClassDataContext _context = new DataClassDataContext();
// GET: Ajax
public ActionResult Data()
{
var series = _context.Tests.Where(t => t.UserId == User.Identity.GetUserId() && t.Units > 0).Select(t => t.Units);
return Json(series, JsonRequestBehavior.AllowGet);
}
}
<script>
var chart;
$(document).ready(function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Blood Glucose Levels'
},
subtitle: {
text: 'Irregular time data in Highcharts JS'
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
},
title: {
text: 'Date'
}
},
yAxis: {
title: {
text: 'Level (mmol/L)'
},
min: 0
},
tooltip: {
headerFormat: '<b>{series.name}</b><br>',
pointFormat: '{point.x:%e. %b}: {point.y:.2f} m'
},
plotOptions: {
spline: {
marker: {
enabled: true
}
}
},
});
function requestData() {
$.ajax({
url: '/Ajax/Data',
type: "GET",
dataType: "json",
success: function (response) {
chart.addSeries({
name: 'level',
data: response
});
},
cache: false
});
}
});
</script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto">
</div>
+3
source to share
No one has answered this question yet
Check out similar questions: