I have some problems need your help. I have a javascript connect to signalr and get data from database. Now I want to get this data and display in data of chart.js . Can you give me some example to do that. Pleas don’t ignore me, I really need your help!
This is code query in HomeController:
public JsonResult Get()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ValueConnection"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(@"SELECT [DeviceID],[Value] FROM [dbo].[Device1] WHERE [DeviceID]='PM1'", connection))
{
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
SqlDataReader reader = command.ExecuteReader();
var listCus = reader.Cast<IDataRecord>()
.Select(x => new
{
DeviceID = (string)x["DeviceID"],
Value = (double)x["Value"],
}).ToList();
return Json(new { listCus = listCus }, JsonRequestBehavior.AllowGet);
}
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
CusHub.Show();
}
Javascript connect to SignalR and get data from JsonResult :
<script type="text/javascript">
$(function () {
//Proxy created on the fly
var cus = $.connection.cusHub;
//Declare a function on the job hub so the server can invoke
cus.client.displayValue = function () {
getData();
};
//Start the connection
$.connection.hub.start();
getData();
});
function getData() {
var $tbl = $('#tblValue');
$.ajax({
url: $("#Get").val(),
type: 'GET',
datatype: 'json',
success: function (data) {
$tbl.empty();
$.each(data.listCus, function (i, model) {
$tbl.append
(
//'<tr>' +
//'<td>' + model.DeviceID + '</td>' +
//'<td>' + model.Value + '</td>' +
//'</tr>'
model.Value
);
});
}
});
}
</script>
And how can I get data from the above script and display in data of chart.js script :
<script>
var ctx = document.getElementById("percent-chart2");
function DynamicFunction() {
var my_val = parseFloat(document.getElementById("tblValue").innerHTML);
return my_val;
}
if (ctx) {
ctx.height = 209;
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
datasets: [
{
label: "My First dataset",
//data: [my_val1, my_val1, my_val1],
data: [my_val, my_val, my_val],
backgroundColor: [
'#00b5e9',
'#fa4251',
'#006400'
],
hoverBackgroundColor: [
'#00b5e9',
'#fa4251',
'#006400'
],
borderWidth: [
0, 0, 0
],
hoverBorderColor: [
'transparent',
'transparent',
'transparent'
]
}
],
labels: [
'STATION 1',
'STATION 2',
'STATION 3'
]
},
options: {
maintainAspectRatio: false,
responsive: true,
cutoutPercentage: 87,
animation: {
animateScale: true,
animateRotate: true
},
legend: {
display: false,
position: 'bottom',
labels: {
fontSize: 14,
fontFamily: "Poppins,sans-serif"
}
},
tooltips: {
titleFontFamily: "Poppins",
xPadding: 15,
yPadding: 10,
caretPadding: 0,
bodyFontSize: 16,
}
}
});
}
</script>