grafico a barre semplice nel Highcharts jQuery e MVC 2 applicazione?
-
11-10-2019 - |
Domanda
Sto cercando di creare un semplice grafico a barre utilizzando i risultati di un metodo di azione JSON in MVC. Ottengo il grafico a barre vero e proprio, ma non capisco le opzioni e tutto il resto abbastanza bene, quindi sono fondamentalmente cercando di indovinare che cosa fare. Ho usato l'esempio sul sito Highcharts come esempio per come ottenere i dati dal codice server e creare un grafico. La differenza è mia tabella è più semplice l'esempio. Non ho le categorie per ogni utente (come nell'esempio di frutta), ho solo un utente e un numero di ore registrate.
Ecco il codice dei Highcharts jQuery:
function getHighChart() {
var actionUrl = '<%= Url.Action("GetChartData") %>';
var customerId = $('#customersId').val();
var startdate = $('.date-pickStart').val();
var enddate = $('.date-pickEnd').val();
var options = {
chart: {
renderTo: 'chart-container',
defaultSeriesType: 'bar'
},
title: {
text: 'Statistik'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Timmar'
}
},
series: []
}
jQuery.getJSON(actionUrl,
{ customerId: customerId, startdate: startdate, enddate: enddate }, function (items) {
var series = {
data: []
};
$.each(items, function (itemNo, item) {
series.name = item.Key;
series.data.push(parseFloat(item.Value));
});
options.series.push(series);
var chart = new Highcharts.Chart(options);
});
}
Ed ecco il metodo di azione di richiamo JSON:
public JsonResult GetChartData(string customerId, string startdate, string enddate)
{
int intcustomerId = Int32.Parse(customerId);
var emps = from segment in _repository.TimeSegments
where
segment.Date.Date >= DateTime.Parse(startdate) &&
segment.Date.Date <= DateTime.Parse(enddate)
where segment.Customer.Id == intcustomerId
group segment by segment.Employee
into employeeGroup
select new CurrentEmployee
{
Name = employeeGroup.Key.FirstName + " " + employeeGroup.Key.LastName,
CurrentTimeSegments = employeeGroup.ToList(),
CurrentMonthHours = employeeGroup.Sum(ts => ts.Hours)
};
Dictionary<string, double > retVal = new Dictionary<string, double>();
foreach (var currentEmployee in emps)
{
retVal.Add(currentEmployee.Name, currentEmployee.CurrentMonthHours);
}
return Json(retVal.ToArray(), JsonRequestBehavior.AllowGet);
}
sono stato in grado di creare un grafico a torta, ma ora quando voglio creare una barra semplice io non sono in grado di capire che cosa è ciò che nel codice jQuery, quindi i risultati che ottengo è un bar dove prima di tutto l'unico utente elencato nella legenda è l'ultimo nella matrice. In secondo luogo, gli spettacoli tooltip x = [nome dell'utente], y = 29, invece di [nome dell'utente]:. 29, che ho preso nel grafico
Come faccio a creare come un semplice grafico a barre in Highcharts da questo JSON?
Soluzione 2
Bene, ho lavorato fuori io stesso, dopo tutto ... ho pensato di postare in caso alcuni altri Highcharts newbie come me è interessato:
Ecco il jQuery che ha funzionato:
function getHighChart() {
var actionUrl = '<%= Url.Action("GetChartData") %>';
var customerId = $('#customersId').val();
var customerName = $('#customersId option:selected').text();
var startdate = $('.date-pickStart').val();
var enddate = $('.date-pickEnd').val();
//define the options
var options = {
chart: {
renderTo: 'chart-container',
defaultSeriesType: 'column'
},
title: {
text: 'Hours worked for ' + customerName
},
xAxis: {
categories: [customerName]
},
yAxis: {
title: {
text: 'Hours'
}
},
series: []
};
//Calls the JSON action method
jQuery.getJSON(actionUrl,
{ customerId: customerId, startdate: startdate, enddate: enddate }, function (items) {
$.each(items, function (itemNo, item) {
var series = {
data: []
};
series.name = item.Key;
series.data.push(parseFloat(item.Value));
options.series.push(series);
});
var chart = new Highcharts.Chart(options);
});
}
Se qualcuno può trovare difetti in questo e mi puntare a un modo migliore per farlo, sarò contento di cedere il credito risposta, altrimenti io accettare la mia risposta ...
Altri suggerimenti
Io uso:
//Controller action:
public JsonResult GetData(int id)
{
Dictionary<int, double> data = this.repository.GetData(id);
return Json(data.ToArray(), JsonRequestBehavior.AllowGet);
}
Visualizza:
<script>
var chart1;
$(document).ready(function () {
chart1 = new Highcharts.Chart({
chart: {
renderTo: 'chart-container-1',
defaultSeriesType: 'scatter',
events: {
load: requestData
}
},
options...
,
series: [{
name: 'some data',
data: []
}]
});
}
);
function requestData() {
$.ajax({
url: '/ControllerName/GetData?id=@(Model.Id)',
success: function (items) {
$.each(items, function (itemNo, item) {
chart1.series[0].addPoint([item.Key,item.Value], false);
});
chart1.redraw();
},
cache: false
});
}
</script>
<div id="chart-container-1"></div>
Quindi sostanzialmente uso addPoint ( 'array di x, y', false per non ridisegnare grafico)