天天看點

highcharts mvc ajax,javascript - Highcharts,AJAX and MVC - Stack Overflow

There seems to be a lot of fusion regarding MVC, Ajax and Highcharts so I thought I'd post my approach, it's all very simple and I hope it helps someone.

From a simple controller the returns an array of doubles from a DB to the rendering of the 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);

}

}

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: '

{series.name}

',

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

});

}

});