Plot Highchart Gauge with JSON Data - c#

How do I plot highchart Gauge with JSON Data?
I am working on highchart gauge, I got succes in showing the latest data from the database. I used JavaScriptSerializer for that
The code is..
<script type="text/javascript">
$(function () {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'gauge',
plotBackgroundColor: null,
plotBackgroundImage: null,
plotBorderWidth: 0,
plotShadow: false
},
//Other char parameter comes here
}
function (chart) {
setInterval(function () {
$.getJSON("S14.aspx", function (data, textStatus) {
console.log(data);
$.each(data, function (index, wind) {
var point = chart.series[0].points[0],
newVal = wind;
point.update(newVal);
});
});
}, 3000);
});
The code for JSON is
public string chartData1
{
get;
set;
}
protected void Page_Load(object sender, EventArgs e)
{
List<double> _data = new List<double>();
GetData();
foreach (DataRow row in dt.Rows)
{
_data.Add((double)Convert.ToDouble(row["S11"]));
}
JavaScriptSerializer jss = new JavaScriptSerializer();
chartData1 = jss.Serialize(_data);
}
My JSON looks like
[1387204961992.4268,72]
Well the problem is that the dial of gauge is not moving according to the last values i need to refresh the page for that. I know this is happening because the GetData function is being executed only one time. I am stuck here.
How do I get the dial move according to the last values updates in the database?

Try to place this part of code
setInterval(function() {
$(function() {
$.getJSON('S12.aspx', function(data) {
$.each(data, function(val) {
if (val !== null)
{
var point = chart.series[0].points[0];
point.update(val);
}
});
});
})
},2000)
Inside callback chart, like here: http://www.highcharts.com/demo/gauge-speedometer
If you receive any errors,please attach.

I think there is a bug or something in the visual studio 2012 . I just paste the entire code on the new aspx page it it got working. I have not done anything else I just pasted the code on another page.
<script type="text/javascript">
$(function () {
$('#container1').highcharts({
chart: {
type: 'gauge',
alignTicks: false,
plotBackgroundColor: null,
plotBackgroundImage: null,
plotBorderWidth: 0,
plotShadow: false
},
title: {
text: 'Pressure Meter'
},
pane: {
startAngle: -150,
endAngle: 150
},
yAxis: [{
min: 0,
max: 1000,
lineColor: '#339',
tickColor: '#339',
minorTickColor: '#339',
offset: -25,
lineWidth: 2,
labels: {
distance: -20,
rotation: 'auto'
},
tickLength: 5,
minorTickLength: 5,
endOnTick: false
}, {
min: 0,
max: 1000,
tickPosition: 'outside',
lineColor: '#933',
lineWidth: 2,
minorTickPosition: 'outside',
tickColor: '#933',
minorTickColor: '#933',
tickLength: 5,
minorTickLength: 5,
labels: {
distance: 12,
rotation: 'auto'
},
offset: -20,
endOnTick: false
}],
series: [{
name: 'Pressure',
data: [80],
dataLabels: {
formatter: function () {
var psi = this.y,
bar = Math.round(psi / 14.50);
return '<span style="color:#339">' + psi + ' psi</span><br/>' +
'<span style="color:#933">' + bar + ' bar</span>';
},
backgroundColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, '#DDD'],
[1, '#FFF']
]
}
},
tooltip: {
valueSuffix: ' psi'
}
}]
},
// Add some life
function (chart) {
setInterval(function () {
$.getJSON("S12.aspx", function (data, textStatus) {
$.each(data, function (index, wind) {
var point = chart.series[0].points[0],
newVal = wind;
point.update(newVal);
});
});
}, 3000);
});
});
</script>

In order for the chart to update, the browser somehow needs to request the latest data from the server. There are two ways it can do this:
A page refresh - the whole page is fetched again, with the latest data.
An Ajax request. This makes a request for just the data, without re-loading the entire page.
I presume you would like to update the chart without reloading the entire page. In order do to this, you need to find out about making ajax requests using jquery.
The highcharts site has some resources which will help you (e.g. http://www.highcharts.com/docs/working-with-data/preprocessing-live-data). You need to learn how to make an ajax call in javascript, and use the returned data to update your chart. You will also need to write the server side part which returns the ajax data. The example given is in php, but it should be fairly straight forward to do something similar in asp.net.

Related

Highsoft.Highstock .NET - How to update navigation on all charts with MVC

I am using Highsoft.Highstock .NET on my ASP.net MVC 5 application.
I create a list of single line charts directly inside the controller and send all the data to the view.
When I change the navigation (start/enddate slider at the bottom of the chart) for one chart, I would like to update all other charts to the same timeframe (all charts have the same timespan).
I would like to do this with jquery, but I am not able right now.
I think I have to use the
(I was also reading the API from Highstock but there is something different, e.g.: my charts do not have a property "chart.title.text" -> my one has "chart.title.textStr")
JS solution:
To update all charts when you change the navigator position on one of them you can use xAxis.events.afterSetExtremes event to set new extremes on all charts (you can find all charts reference in Highcharts.charts array).
Code:
var json = "[[1534512600000,217.58],[1534771800000,215.46],[1534858200000,215.04],[1534944600000,215.05],[1535031000000,215.49],[1535117400000,216.16],[1535376600000,217.94],[1535463000000,219.7],[1535549400000,222.98],[1535635800000,225.03],[1535722200000,227.63],[1536067800000,228.36],[1536154200000,226.87],[1536240600000,223.1],[1536327000000,221.3],[1536586200000,218.33],[1536672600000,223.85],[1536759000000,221.07],[1536845400000,226.41],[1536931800000,223.84],[1537191000000,217.88],[1537277400000,218.24],[1537363800000,218.37],[1537450200000,220.03],[1537536600000,217.66],[1537795800000,220.79],[1537882200000,222.19],[1537968600000,220.42],[1538055000000,224.95],[1538141400000,225.74],[1538400600000,227.26],[1538487000000,229.28],[1538573400000,232.07],[1538659800000,227.99],[1538746200000,224.29],[1539005400000,223.77],[1539091800000,226.87],[1539178200000,216.36],[1539264600000,214.45],[1539351000000,222.11],[1539610200000,217.36],[1539696600000,222.15],[1539783000000,221.19],[1539869400000,216.02],[1539955800000,219.31],[1540215000000,220.65],[1540301400000,222.73],[1540387800000,215.09],[1540474200000,219.8],[1540560600000,216.3],[1540819800000,212.24],[1540906200000,213.3],[1540992600000,218.86],[1541079000000,222.22],[1541165400000,207.48],[1541428200000,201.59],[1541514600000,203.77],[1541601000000,209.95],[1541687400000,208.49],[1541773800000,204.47],[1542033000000,194.17],[1542119400000,192.23],[1542205800000,186.8],[1542292200000,191.41],[1542378600000,193.53],[1542637800000,185.86],[1542724200000,176.98],[1542810600000,176.78],[1542983400000,172.29],[1543242600000,174.62],[1543329000000,174.24],[1543415400000,180.94],[1543501800000,179.55],[1543588200000,178.58],[1543847400000,184.82],[1543933800000,176.69],[1544106600000,174.72],[1544193000000,168.49],[1544452200000,169.6],[1544538600000,168.63],[1544625000000,169.1],[1544711400000,170.95],[1544797800000,165.48],[1545057000000,163.94],[1545143400000,166.07],[1545229800000,160.89],[1545316200000,156.83],[1545402600000,150.73],[1545661800000,146.83],[1545834600000,157.17],[1545921000000,156.15],[1546007400000,156.23],[1546266600000,157.74],[1546439400000,157.92],[1546525800000,142.19],[1546612200000,148.26],[1546871400000,147.93],[1546957800000,150.75],[1547044200000,153.31],[1547130600000,153.8]]";
var data = JSON.parse(json);
function updateExtremes() {
var currentChart = this.chart,
chartIndex = currentChart.index,
charts = Highcharts.charts,
min = currentChart.xAxis[0].min,
max = currentChart.xAxis[0].max;
charts.forEach(function(chart) {
if (chart.index !== chartIndex) {
chart.xAxis[0].setExtremes(min, max, true, false);
}
});
}
Highcharts.stockChart('container1', {
chart: {
height: 250
},
rangeSelector: {
selected: 0
},
title: {
text: 'AAPL Stock Price'
},
xAxis: {
events: {
afterSetExtremes: function() {
updateExtremes.call(this);
}
}
},
series: [{
name: 'AAPL',
data: data,
tooltip: {
valueDecimals: 2
}
}]
});
Highcharts.stockChart('container2', {
chart: {
height: 250
},
rangeSelector: {
selected: 0
},
title: {
text: 'AAPL Stock Price'
},
xAxis: {
events: {
afterSetExtremes: function() {
updateExtremes.call(this);
}
}
},
series: [{
name: 'AAPL',
data: data,
tooltip: {
valueDecimals: 2
}
}]
});
Highcharts.stockChart('container3', {
chart: {
height: 250
},
rangeSelector: {
selected: 0
},
title: {
text: 'AAPL Stock Price'
},
xAxis: {
events: {
afterSetExtremes: function() {
updateExtremes.call(this);
}
}
},
series: [{
name: 'AAPL',
data: data,
tooltip: {
valueDecimals: 2
}
}]
});
Demo:
https://jsfiddle.net/BlackLabel/74rgyq13/
JS API reference:
https://api.highcharts.com/highcharts/xAxis.events.afterSetExtremes
https://api.highcharts.com/class-reference/Highcharts.Axis#setExtremes
C# API reference:
http://dotnet.highcharts.com/Help/Highcharts/html/class_highsoft_1_1_web_1_1_mvc_1_1_charts_1_1_x_axis_events.html#aa8efb1a8237bc71a0268e5ee7e522096
http://dotnet.highcharts.com/Help/Highcharts/html/class_highsoft_1_1_web_1_1_mvc_1_1_charts_1_1_x_axis_events.html#a120bc76164638d4a76a7ee20280d54ff

Using variable from a C# class in a Javascript code with Razor

I'm developing a web application with Telerik Kendo in Razor. Here is my problem:
I have a variable that I set as a type List<class>.
#{
ViewBag.Title = "Home Page";
var dpdminst = new DB();
var data = dpdminst.getdata();}
I want to be able to use this variable (data) to set my DataSource in my Javascript:
<script>
var displaydata = #data
$(document).ready(function () {
$("#grid").kendoGrid({
height: 550,
groupable: true,
sortable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
dataSource: {
data:displaydata,
schema: {
model: {
fields: {
amount: { type: "string" },
}
}
},
columns:["amount"]
}
});
});
</script>
Does anyone know if this can be done?
Here is my JsonResult:
public JsonResult GetJsonData()
{
var DBinst = new DB();
var TradeData = DBinst.tradedata();
var json = JsonConvert.SerializeObject(TradeData);
var result = new JsonResult()
{
Data = json
};
return result;
}
Have an action method which returns the data you want in JSON format. in your document.ready event, make an ajax call to get this data and then you can set it as your data source.
public ActionResult GetJsonData()
{
var dpdminst = new DB();
var data = dpdminst.getdata();
return Json(data,JsonRequestBehaviour.AllowGet);
}
and in your view use the getJSON method to get data from this action method and use that as needed. You may format the incoming json as per your UI requirements
$(document).ready(function () {
$.getJSON("#Url.Action("GetJsonData","YourControllerName")",function(data){
// you have your json data in the "data" variable.
// now you may use it to set the data source of your grid library
});
});
If you dont want to deal with ajax/json, then I would try to achieve what you want as follows:
<script>
var displaydata = [
#foreach (var record in dpdminst.getdata())
{
#: { amount: '#record' },
}
];
$(document).ready(function () {
$("#grid").kendoGrid({
height: 550,
groupable: true,
sortable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
dataSource: {
data:displaydata,
schema: {
model: {
fields: {
amount: { type: "string" },
}
}
},
},
columns:["amount"]
});
});
</script>
Also please notice that you had columns:["amount"] in a wrong place, also this code has to be in your cshtml for razor syntax to work properly.

Qtip data not defined error

I am using Qtip tooltip and my content is from JSON.
When i click the tooltip to display the content, i get an error that 'data is not defined' when inspecting the element in chrome.
This is my javascript code.
$('#accordion_functions ul li a span:nth-child(2)').each(function () {
$(this).qtip({
content: {
text: function(event,api) {
$.ajax({
url: 'http://localhost:51783/Help/GetHelpText.ashx',
type: 'GET',
dataType: 'json',
data: {
id: $(this).attr('id') // Pass through the ID span
},
})
.then(function(content) {
var content = 'Help' + data.Text;
api.set('content.text', content);
}, function(xhr, status, error) {
api.set('content.text', status + ': ' + error);
});
return 'Loading' // Set some initial loading text
}
},
hide: {
event: 'click',
fixed: true,
delay: 50
},
show: {
event: 'click',
solo: true
},
events: {
show: function (event, api) {
$(api.elements.target).addClass('highlight');
},
hide: function (event, api) {
$(api.elements.target).removeClass('highlight');
}
},
style: {
width: 1200,
padding: 5,
tip: 'bottomRight',
},
position: {
my: 'bottom right',
at: 'bottom middle'
}
});
The data posted by the url looks like this:
[{"id":"PCG01","Form":"Party Company","Tab":"General","Text":"Help needed here"},{"id":"PCG02","Form":"Party Company","Tab":"Contact","Text":"This is a second help"},{"id":"PCG03","Form":"Party Company","Tab":"Settlement","Text":"Third help"},{"id":"PCG04","Form":"Party Company","Tab":"Client","Text":"Fourth help"},{"id":"PCG05","Form":"Party Company","Tab":"Trade Constraints","Text":"Fifth help"},{"id":"PCG06","Form":"Party Company","Tab":"Attachments","Text":"Sixth help"}]
What could i be doing wrong?
isn't it in the .then
.then(function(content) {
var **contentText** = 'Help' + **content**.Text;
api.set('content.text', **contentText**);
The problem was in the .then. I were basically accessing the json object in a wrong way.
I changed .then from:
.then(function(content) {
var content = 'Help' + data.Text;
api.set('content.text', content);
},
To:
.then(function(content) {
var content = 'Help' + content[0].Text +'';
api.set('content.text', content);
},

asp:HiddenField get value from JavaScript Variable upon Button Click

I am quite new to JavaScript and jQuery, although I have often used jQuery UI Components, I barely made any modifications before. In this case, I needed to adjust the jQuery Slider to adjust the date, and I created something as the following: http://jsfiddle.net/ryn_90/Tq7xK/6/.
I'm happy with that so far, and now that I got the slider working as I would like it to, I would like to be able to bind a C# HiddenValue from the JavaScript attribute or from the HTML so I can save the date I have. Unless there is any better method to get this value to the backend...
So far I have been able to bind a JavaScript value from c# variables, but have not found out how to do it the other way round.
This is my javascript code:
<script>
$(function () {
$("#dialog").dialog({
autoOpen: false,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
}
});
jQuery(function() {
var dlg = jQuery("#sliderPopup").dialog({
draggable: true,
resizable: true,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
},
width: 320,
autoOpen: false,
minHeight: 10,
minwidth: 10
});
dlg.parent().appendTo(jQuery("form"));
});
$("#popupOpener").click(function () {
$("#dialog").dialog("open");
});
$("#sliderPopupOpener").click(function () {
$("#sliderPopup").dialog("open");
});
});
$(function () {
$("#slider").slider({
max: 30,
min: -30,
value: 0,
slide: function (event, ui) {
$("#days").val(ui.value);
$("#date").text(addDaysToDate(parseInt($("#days").val())));
},
create: function (event, ui) {
$("#date").text(addDaysToDate(parseInt($("#days").val())));
}
});
});
$("#days").val($("#slider").slider("value"));
$("#days").change(function (event) {
var data = $("#days").val();
if (data.length > -30) {
if (parseInt(data) >= 0 && parseInt(data) <= 30) {
$("#slider").slider("option", "value", data);
}
else {
if (parseInt(data) < -30) {
$("#days").val("-30");
$("#slider").slider("option", "value", "-30");
}
if (parseInt(data) > 30) {
$("#days").val("30");
$("#slider").slider("option", "value", "30");
}
}
}
else {
$("#slider").slider("option", "value", "0");
}
$("#date").text(addDaysToDate(parseInt($("#days").val())));
});
function addDaysToDate(days) {
var mths = new Array("Jan", "Feb", "Mar",
"Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec");
var d = new Date(<%=deadlineYear%>, <%=deadlineMonth%>, <%=deadlineDay%>);
d.setHours(d.getHours() + (24 * days));
var currD = d.getDate();
var currM = d.getMonth();
var currY = d.getFullYear();
return mths[currM] + " " + currD + ", " + currY;
}
jQuery(function() {
var dlg = jQuery("#sliderPopup").dialog({
draggable: true,
resizable: true,
show: 'Transfer',
hide: 'Transfer',
width: 320,
autoOpen: false,
minHeight: 10,
minwidth: 10
});
dlg.parent().appendTo(jQuery("form"));
});
</script>
This is the asp.NET Code:
<div id="sliderPopup" title="Modify Deadline">
<div id="slider"></div>
<input type="text" id="days" value="0"/>
<div id="date"></div>
<asp:HiddenField ID="ModifiedDeadlineDateFromSlider" />
<asp:Button ID="DeadlineDateSave" Text="Save Deadline" runat="server" OnClick="saveDeadline" />
</div>
Please let me know if you need any more information. I would appreciate your answers and comments.
You can set the date value to the hidden field by adding just single line of code. Add the following code inside the slide event and the create event of your .slider function
$("#ModifiedDeadlineDateFromSlider").val(addDaysToDate(parseInt($("#days").val())));
or
$("#ModifiedDeadlineDateFromSlider").val($("#date").text());
Your .slider function will look like this after the modification.
$(function () {
$("#slider").slider({
max: 30,
min: -30,
value: 0,
slide: function (event, ui) {
$("#days").val(ui.value);
$("#date").text(addDaysToDate(parseInt($("#days").val())));
$("#ModifiedDeadlineDateFromSlider").val($("#date").text());
},
create: function (event, ui) {
$("#date").text(addDaysToDate(parseInt($("#days").val())));
$("#ModifiedDeadlineDateFromSlider").val($("#date").text());
}
});
});
P.S. Add the mentioned line of code to create event only if you want to set date in hidden field value on creation of slider also. If you want to set only if date is changes then just add that code in slide event only.
Note: In this particular scenerio it was not working with the changes also. So after discussion and couple of trials we discovered one more thing which was minor but created the problem. asp hidden field's property ClientIDMode was not set to static due to which its ID was changed during rendering and as a result value was not available in code behind late
Hope that helps!
To pass javascript value to c# do this way:
<script type="text/javascript">
function abc()
{
var str = "yourValue";
document.getElementById("HiddenField1").value = str;
}
</script>
and then access HiddenField1.Value on code-behind.
To pass c# variable to javascript you can bind public variable like this:
<%=this.YourVariable%>

Save state of Widgets in ASP.NET MVC using jQuery and Json

I am using ASP.NET MVC in C#
I have a page where the user can move different Widgets around the page, and I now need a method to save the state of the widgets. I am using jQuery in the HTML page, and the jQuery posts the new page layout using JSON. I am unsure how to read the JSON in the controller.
The code I'm using is based on this example here - http://webdeveloperplus.com/jquery/saving-state-for-collapsible-drag-drop-panels/, but the code for saving the result is in PHP.
jQUERY
<script type="text/javascript" >
$(function () {
$('.dragbox')
.each(function () {
$(this).hover(function () {
$(this).find('h2').addClass('collapse');
}, function () {
$(this).find('h2').removeClass('collapse');
})
.find('h2').hover(function () {
$(this).find('.configure').css('visibility', 'visible');
}, function () {
$(this).find('.configure').css('visibility', 'hidden');
})
.click(function () {
$(this).siblings('.dragbox-content').toggle();
//Save state on change of collapse state of panel
updateWidgetData();
})
.end()
.find('.configure').css('visibility', 'hidden');
});
$('.column').sortable({
connectWith: '.column',
handle: 'h2',
cursor: 'move',
placeholder: 'placeholder',
forcePlaceholderSize: true,
opacity: 0.4,
start: function (event, ui) {
//Firefox, Safari/Chrome fire click event after drag is complete, fix for that
if ($.browser.mozilla || $.browser.safari)
$(ui.item).find('.dragbox-content').toggle();
},
stop: function (event, ui) {
ui.item.css({ 'top': '0', 'left': '0' }); //Opera fix
if (!$.browser.mozilla && !$.browser.safari)
updateWidgetData();
}
})
.disableSelection();
});
function updateWidgetData() {
var items = [];
$('.column').each(function () {
var columnId = $(this).attr('id');
$('.dragbox', this).each(function (i) {
var collapsed = 0;
if ($(this).find('.dragbox-content').css('display') == "none")
collapsed = 1;
//Create Item object for current panel
var item = {
id: $(this).attr('id'),
collapsed: collapsed,
order: i,
column: columnId
};
//Push item object into items array
items.push(item);
});
});
//Assign items array to sortorder JSON variable
var sortorder = { items: items };
//Pass sortorder variable to server using ajax to save state
$.post('/Widgets/SaveLayout', 'data=' + $.toJSON(sortorder), function (response) {
if (response == "success")
$("#console").html('<div class="success">Saved</div>').hide().fadeIn(1000);
setTimeout(function () {
$('#console').fadeOut(1000);
}, 2000);
});
alert(sortorder);
}
I am willing to consider alternative ways to do this, as I may not have chosen the best way to do this.
Phil Haack's blog post http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx specifically handles the problem you are trying to solve and it works great.
Hope this helps.
Why not use a cookie? This would save you from having to pull that data back and forth from the server so much.

Categories

Resources