Multiseries line chart on highcharts - asp.net

i have to create a multiseries line chart which is to need view each series with the value of site id and each series with different position .Just now i'am stuck that can only view one series with one query.
And here is the aspx.vb page
Public Class WaterTreament
Public position As Integer
Public value As Double
Public timestamp As String
End Class
<WebMethod()>
Public Shared Function GetWaterTreament() As List(Of WaterTreament)
Using con As New SqlConnection("Data Source=DESKTOP-B8TBSJH1;Initial Catalog=SAY;Integrated Security=SSPI")
Using cmd As New SqlCommand("select position,dtimestamp ,value from telemetry_log_table where siteid ='S1-21' AND dtimestamp BETWEEN '2021-02-02' AND '2021-02-03' and position='62'and value>0 order by dtimestamp asc")
cmd.Connection = con
Dim wtp As New List(Of WaterTreament)()
con.Open()
Using dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
wtp.Add(New WaterTreament() With {
.position = Convert.ToInt32(dr("position").ToString()),
.value = Convert.ToDouble(dr("value").ToString()),
.timestamp = dr("dtimestamp").ToString()
})
End While
End Using
con.Close()
Return wtp
End Using
End Using
End Function
Here is the script for highcharts.
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebForm1.aspx/GetWaterTreament",
data: "{}",
dataType: "json",
success: OnSuccess_,
error: OnErrorCall_
});
function OnSuccess_(response) {
debugger;
var aData = response.d;
var arr = [];
var arr2 = [];
var timestamp = [];
$.map(aData, function (item, index) {
var i = [item.value];
var obj = {};
var obj1 = {};
var obj2 = {};
obj.name = item.position;
obj.y = item.value;
obj.y1 = item.timestamp;
obj2.data = item.timestamp;
arr.push(obj.y);
arr2.push(obj.y1);
timestamp.push(obj2.data);
console.log(obj2);
});
var myJsonString = JSON.stringify(arr);
var jsonArray = JSON.parse(JSON.stringify(arr));
//Second Value
var myJsonString1 = JSON.stringify(arr2);
var jsonArray1 = JSON.parse(JSON.stringify(arr2));
//third Value
var myJsonString2 = JSON.stringify(timestamp);
var jsonArray2 = JSON.parse(JSON.stringify(timestamp));
//alert(jsonArray);
DreawChart(jsonArray, jsonArray1, jsonArray2);
}
function OnErrorCall_(response) {
alert("Whoops something went wrong!");
}
});
function DreawChart(seriesData1, seriesData2, seriesData3) {
Highcharts.chart('container', {
// $('#container').highcharts({
title: {
text: 'SITE ID'
},
yAxis: {
title: {
text: 'Values',
}
},
xAxis: {
categories: seriesData3
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
}
},
series: [{
type: 'line',
name: 'PH',
data: seriesData1
},
{
type: 'line',
name: 'CHLORINE',
data: seriesData1
},
],
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
}`

What is your issue here exactly?
You may want to try official Highcharts .NET wrapper: dotnet.highcharts.com.
Sample chart and source code in C# with multiple series: https://dotnet.highcharts.com/Highcharts/Demo/Gallery?demo=LineBasic&theme=default

Related

Why highchart not show me in asp.net?

I'm beginner in asp.net and highchart control,want to use highchart control in my web application web form,for that purpose read this tutorial:
this tutorial
and write this web service in my project:
public class cityPopulation
{
public string city_name { get; set; }
public int population { get; set; }
public string id { get; set; }
}
[WebMethod]
public List<cityPopulation> getCityPopulation(List<string> pData)
{
List<cityPopulation> p = new List<cityPopulation>();
cityPopulation cpData = new cityPopulation();
cpData.city_name = "tabriz";
cpData.population = 100;
p.Add(cpData);
return p;
}
that web service name is this:
WebService1.asmx
and in my web form write this script :
<script type="text/javascript">
function drawPieChart(seriesData) {
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Population percentage city wise'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
name: "Brands",
colorByPoint: true,
data: seriesData
}]
});
}
$("#btnCreatePieChart").on('click', function (e) {
var pData = [];
pData[0] = $("#ddlyear").val();
var jsonData = JSON.stringify({ pData: pData });
$.ajax({
type: "POST",
url: "WebService1.asmx/getCityPopulation",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess_,
error: OnErrorCall_
});
function OnSuccess_(response) {
var aData = response.d;
var arr = []
$.map(aData, function (item, index) {
var i = [item.city_name, item.population];
var obj = {};
obj.name = item.city_name;
obj.y = item.population;
arr.push(obj);
});
var myJsonString = JSON.stringify(arr);
var jsonArray = JSON.parse(JSON.stringify(arr));
drawPieChart(jsonArray);
}
function OnErrorCall_(response) {
alert("Whoops something went wrong!");
}
e.preventDefault();
});
//*
</script>
before that script write this code:
<script src="Scripts/jquery-2.2.3.min.js"></script>
<script src="Scripts/Highcharts-4.0.1/js/highcharts.js"></script>
and write this html code:
<select id="ddlyear">
<option>2010</option>
<option>2011</option>
<option>2012</option>
<option>2013</option>
<option>2014</option>
<option>2015</option>
</select>
<button id="btnCreatePieChart">Show </button>
<br />
<div>
<div id="container" style="width: 500px; height: 500px"></div>
</div>
but when i run project and fire the button,can not see anything,and chart not show to me,what happen?is my code incorrect?how can i solve that problem?thanks.
i think ajax can not call the web service!

Morris chart does not display data from external URL

I have a Morris chart that I try to use that gets data from an external source in this case an aspx page. But the chart is not displayed at all. The only chart that is displayed is the one I add static data to myfirstchart.
Anyone see what I am missing?
Chart page:
<head runat="server">
<title></title>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
Morris.Donut({
element: 'morris-donut-chart',
data: $.parseJSON(Graph()),
resize: true
});
});
function Graph() {
var data = "";
$.ajax({
type: 'POST',
url: 'data.aspx',
dataType: 'json',
async: false,
contentType: "application/json; charset=utf-8",
data: {},
success: function (result) {
data = result.d;
},
error: function (xhr, status, error) {
alert(error);
}
});
return data;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="morris-donut-chart" style="height: 250px;"></div>
<div id="myfirstchart" style="height: 250px;"></div>
</div>
</form>
<script>
new Morris.Line({
// ID of the element in which to draw the chart.
element: 'myfirstchart',
// Chart data records -- each entry in this array corresponds to a point on
// the chart.
data: [
{ year: '2008', value: 20 },
{ year: '2009', value: 10 },
{ year: '2010', value: 5 },
{ year: '2011', value: 5 },
{ year: '2012', value: 20 }
],
// The name of the data record attribute that contains x-values.
xkey: 'year',
// A list of names of data record attributes that contain y-values.
ykeys: ['value'],
// Labels for the ykeys -- will be displayed when you hover over the
// chart.
labels: ['Value']
});
</script>
</body>
Data page:
protected void Page_Load(object sender, EventArgs e)
{
var sb = new StringBuilder();
sb.Append("[");
sb.Append(" { label: '2012-10-01', value: 802 },");
sb.Append(" { label: '2012-10-02', value: 783 },");
sb.Append(" { label: '2012-10-03', value: 820 },");
sb.Append(" { label: '2012-10-04', value: 839 },");
sb.Append(" { label: '2012-10-05', value: 792 },");
sb.Append(" { label: '2012-10-06', value: 859 },");
sb.Append(" { label: '2012-10-07', value: 790 },");
sb.Append("]");
var jsonSerializer = new JavaScriptSerializer();
string data = jsonSerializer.Serialize(sb.ToString());
string json = data;
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(json);
Response.End();
}
Use a WebMethod:
[WebMethod]
public static string getGraph()
{
List<object> json = new List<object>();
json.Add(new { label = "2012-10-01", value = 802 });
json.Add(new { label = "2012-10-02", value = 783 });
json.Add(new { label = "2012-10-03", value = 820 });
json.Add(new { label = "2012-10-04", value = 839 });
json.Add(new { label = "2012-10-05", value = 792 });
json.Add(new { label = "2012-10-06", value = 859 });
json.Add(new { label = "2012-10-07", value = 790 });
List<object> jsonObject = new List<object>();
jsonObject.Add(new {
graph = json
});
return new JavaScriptSerializer().Serialize(jsonObject); ;
}
And update your javascript with a call to the WebMethod getGraph:
$(document).ready(function () {
var graph = Graph();
Morris.Donut({
element: 'morris-donut-chart',
data: graph[0].graph,
resize: true
});
});
function Graph() {
var data = "";
$.ajax({
type: 'POST',
url: 'data.aspx/getGraph',
dataType: 'json',
async: false,
contentType: "application/json; charset=utf-8",
data: {},
success: function (result) {
data = $.parseJSON(result.d);
},
error: function (xhr, status, error) {
alert(error);
}
});
return data;
}

jqgrid edit call ajax every time

I'm trying to use jqgrid edit form, but I can't understand why jqgrid do not call asmx web method every time I select a row and I click on edit icon (jqgrid call ajax just the first time)
This is the code:
function Grid() {
var ret = Array();
var grid = jQuery("#grid");
var hideLoading = function () {
$("#lui_" + grid).hide();
$("#load_" + grid).hide();
}
var strSearch = "";
var strField = "";
var strOper = "";
//
// handler: si occupa di creare il contenuto del menu a tendina (form jqGrid)
//
var buildOptions = function (dataList) {
var response = dataList;
var option = "";
if (response && response.length) {
for (var i = 0, l = response.length; i < l; i++) {
if (response[i]["selectedvalue"] == "on")
option += '<option role="option" selected="selected" value="' + response[i]["Codice"] + '">' + response[i]["Descrizione"] + '</option>';
else
option += '<option role="option" value="' + response[i]["Codice"] + '">' + response[i]["Descrizione"] + '</option>';
}
}
return option;
};
grid.jqGrid({
// setup custom parameter names to pass to server
prmNames: {
search: "isSearch",
nd: null,
rows: "numRows",
page: "page",
sort: "sortField",
order: "sortOrder"
},
// add by default to avoid webmethod parameter conflicts
postData: {
searchString: '',
searchField: '',
searchOper: ''
},
// setup ajax call to webmethod
datatype: function (postdata) {
$.ajax({
url: '<%# ResolveUrl("~/Service/Domain/ServiceRoom.asmx/GetRoomRateDiscount") %>',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postdata),
dataType: "json",
success: function (data, st) {
if (data.d == "KO") {
grid.GridUnload();
jAlert("La ricerca non ha restituito alcun risultato", "Book2Guest");
return false;
}
if (st == "success") {
var grid = $("#grid")[0];
grid.addJSONData(JSON.parse(data.d));
ret = JSON.parse(data.d);
}
},
error: function (xhr, textStatus, errorThrown) {
jAlert("Si รจ verificato un errore: " + textStatus + " " + errorThrown + " -- " + $.parseJSON(xhr.statusText), "Book2Guest");
}
});
},
// this is what jqGrid is looking for in json callback
jsonReader: {
root: "rows",
page: "page",
total: "totalpages",
records: "totalrecords",
cell: "cell",
id: "id",
userdata: "userdata",
repeatitems: true
},
ajaxSelectOptions: {
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
data: {
rowId: function () {
if (JSON.stringify(grid.jqGrid('getRowData', grid.jqGrid('getGridParam', 'selrow'))['Codice']) == undefined)
return "";
return JSON.stringify(grid.jqGrid('getRowData', grid.jqGrid('getGridParam', 'selrow'))['Codice']);
}
}
},
colNames: ['ID', 'Rate'],
colModel: [
{ name: 'ID', index: 'ID', width: 10, align: "center", search: false, sorttype: 'int', searchoptions: { sopt: ['eq', 'ne', 'cn']} },
{
name: 'TariffaCodiceOfferta',
index: 'TariffaCodiceOfferta',
width: 50,
hidden: true,
formatter: 'select',
editable: true,
edittype: 'select',
editrules: { edithidden: true }, //, required: true },
editoptions: {
multiselect: true,
dataUrl: '<%# ResolveUrl("~/Service/Domain/ServiceRoom.asmx/GetRoomRateListByRowId") %>',
buildSelect: function (data) {
var response = $.parseJSON(data.d);
var option = buildOptions(response);
var s = '<select>';
s += option;
return s + "</select>";
},
dataInit: function (elem) {
setTimeout(function () {
$(elem).multiselect({ selectedList: 10 });
}, 50);
},
multiple: true
}
},
],
rowNum: 10,
rowList: [10, 20, 30],
height: 'auto',
pager: '#gridpager',
viewrecords: true,
shrinkToFit: false,
loadComplete: function () {
hideLoading();
},
loadError: function () {
hideLoading();
},
editurl: '<%# ResolveUrl("~/Service/Domain/ServiceRoom.asmx/SaveRoomDiscount") %>',
sortname: "ID",
sortorder: "asc",
caption: "Rate list",
onSelectRow: function (id, status) {},
ondblClickRow: function (rowid) {
grid.jqGrid('editGridRow', rowid,
{
width: 450,
height: 450,
closeOnEscape: true,
addCaption: "Add Rate",
editCaption: "Edit Rate",
bSubmit: "Salva",
bCancel: "Annulla",
bClose: "Chiudi",
bYes: "Si",
bNo: "No",
bExit: "Annulla",
editData: {
"codice": function () {
var selectedRow = grid.getGridParam("selrow");
var rowData = grid.getRowData(selectedRow);
return rowData["Codice"];
}
},
viewPagerButtons: false,
closeAfterEdit: true,
reloadAfterSubmit: true,
beforeShowForm: function (form) {
var dlgDiv = $("#editmod" + grid[0].id);
var parentDiv = dlgDiv.parent(); // div#gbox_list
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
// Grabbed jQuery for grabbing offsets from here:
//http://stackoverflow.com/questions/3170902/select-text-and-then-calculate-its-distance-from-top-with-javascript
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
dlgDiv[0].style.top = Math.round(parentTop + (parentHeight - dlgHeight) / 2) + "px";
dlgDiv[0].style.left = Math.round(parentLeft + (parentWidth - dlgWidth) / 2) + "px";
},
onClose: function (response, postdata) {
}
});
return;
},
gridComplete: function () {
if (grid.getGridParam('records') == 0) // are there any records?
DisplayEmptyText(true);
else
DisplayEmptyText(false);
},
emptyDataText: 'There are no records. '
})
grid.setGridWidth(900, true);
grid.jqGrid('navGrid', '#gridpager',
{
edit: true,
view: false,
add: false,
del: true,
search: false
},
//prmEdit
{
width: 450,
height: 300,
closeOnEscape: true,
addCaption: "Aggiungi Offerta",
editCaption: "Modifica Offerta",
bSubmit: "Salva",
bCancel: "Annulla",
bClose: "Chiudi",
saveData: "Sono state apportate delle modifiche, sei sicuro di voler continuare?",
bYes: "Si",
bNo: "No",
bExit: "Annulla",
editData: {
"Codice": function () {
var selectedRow = grid.getGridParam("selrow");
var rowData = grid.getRowData(selectedRow);
return rowData["Codice"];
}
},
viewPagerButtons: false,
closeAfterEdit: true,
reloadAfterSubmit: true,
beforeShowForm: function (form) {
var dlgDiv = $("#editmod" + grid[0].id);
var parentDiv = dlgDiv.parent(); // div#gbox_list
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
// Grabbed jQuery for grabbing offsets from here:
//http://stackoverflow.com/questions/3170902/select-text-and-then-calculate-its-distance-from-top-with-javascript
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
dlgDiv[0].style.top = Math.round(parentTop + (parentHeight - dlgHeight) / 2) + "px";
dlgDiv[0].style.left = Math.round(parentLeft + (parentWidth - dlgWidth) / 2) + "px";
},
onClose: function (response, postdata) {}
}
//prmSearch,
//prmView
);
return ret;
}
UPDATE: to solve this issue, you guys have to insert 'recreateForm: true' in the edit section of jqGrid
You current code don't have 'Codice' column in colModel, but you try to get the data from the column. Even if the original server response has the Codice property, the property will be saved only if you add additional hidden column with the same name.
Sorry, but to tell the trust I would recommend you to rewrite the whole code which you use. The usage of datatype as function is not good. Instead of that you can use jsonReader. The call JSON.parse(data.d) inside of $.ajax having dataType: "json" shows that you did one more important error in the webmethod on the server side. It shows that you make manual conversion of returned object to String instead of returning object from the web method. WebService convert the object to JSON automatically. Because of manual convention to JSON the returned data will be twice converted to JSON. Only because of the error in the server code you have to use JSON.parse(data.d) and can't just use jsonReader like described here for example.

Highcharts with ajax and json data what am i doing wrong?

I have been trying for days to plot a simple line graph utilising HighchartsJS via ajax. I have tried posting on their forum but help seem to be slow in coming forward.
I am using ASP.NET web forms.
Server Side
<WebMethod(EnableSession:=True)> _
Public Function getData() As String
Dim dr As DataRepository = New DataRepository
Dim data As List(Of ArrayList) = New List(Of ArrayList)
For Each q In dr.getAllData()
Dim a As New ArrayList
Dim d As Date = q.DateTime
a.Add(d.Ticks)
a.Add(q.TotalRevenue)
data.Add(a)
Next
Dim ser As Serie = New Serie(data)
Dim str As String = JsonConvert.SerializeObject(ser)
Return str
End Function
This returns the following json object, Please note the double quotes wrapping everything.
"{"data":
[
[634420512000000000,100000.0000],
[634421376000000000,100086.0000],
[634422240000000000,100171.0000],
[634423104000000000,100257.0000]
]
}"
Clientside i am calling the above function and rendering my chart like so.
$(document).ready(function () {
var options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'line'
},
title: {},
xAxis: {
type: 'datetime'
},
yAxis: {},
series: []
};
$.ajax({
type: "POST",
dataType: "json",
data: "{}",
contentType: "application/json; charset=utf-8",
url: "_services/ScriptService.asmx/getData",
success: function (items) {
var obj = jsonParse(items.d);
var series = { data: [] };
$.each(obj, function (itemNo, item) {
series.data.push(item);
});
options.series.push(series);
},
cache: false,
error: function (XMLHttpRequest, textStatus, errorThrown) { alert(errorThrown); }
});
chart = new Highcharts.Chart(options);
});
'items' in the above call is as follows;
"{"data":
[
[634420512000000000,100000.0000],
[634421376000000000,100086.0000],
[634422240000000000,100171.0000],
[634423104000000000,100257.0000]
]
}"
I use 'jsonParser(items.d') to create a correct json object(removing the double quotes).
'obj' now contains my json object and 'item' when inspected in firebug now looks like this;
[
[634420512000000000, 100000],
[634421376000000000, 100086],
[634422240000000000, 100171],
[634423104000000000, 100257]
]
When my chart renders, the points do not get plotted. What am I doing wrong?
Solved the issue.
Needed to change the line
series.data.push(obj.data);
to;
series.data = obj.data;
Put chart = new Highcharts.Chart(options); inside success event.
Solved the issue.
Needed to change the line
series.data.push(obj.data);
to;
series.data = obj.data;

Simple bar chart in jQuery HighCharts and MVC 2 application?

I'm trying to create a very simple bar chart using the results of a JSon action method in MVC. I get the actual bar chart, but I don't understand the options and all that well enough, so I'm basically guessing what to do. I used the example on the HighCharts site as an example for how to get data from server code and create a chart. The difference is my chart is simpler than the example. I don't have categories for each user (as in the fruit example), I only have a user and a number of hours logged.
Here's the HighCharts jQuery code:
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);
});
}
And here's the action method returning 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);
}
I was able to create a pie chart, but now when I want to create a simple bar I'm not able to work out what is what in the jQuery code, so the results I get is a bar where first of all the only user listed in the legend is the last one in the array. Secondly, the tooltip shows x = [The user's name], y = 29, instead of [The user's name]: 29, which I got in the pie chart.
How would I create such a simple bar chart in HighCharts from this JSon?
I use:
//Controller action:
public JsonResult GetData(int id)
{
Dictionary<int, double> data = this.repository.GetData(id);
return Json(data.ToArray(), JsonRequestBehavior.AllowGet);
}
View:
<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>
So basically I use addPoint('array of x,y',false for not redrawing chart)
Well, I worked it out myself after all... I thought I should post it in case some other HighCharts newbie like me is interested:
Here's the jQuery that worked:
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);
});
}
If someone can find faults in this and point me to a better way to do it, I'll gladly hand over the answer credit, otherwise I'll accept my own answer...

Resources