I want to import the data from JSON file into my VS2012 c# code so that I can plot my highcharts based on the data in JSON file.
I have checked many video on youtube and file docs but couldnt locate single code that runs and give an output as required.
Do give me a sample code that will map a data from JSON file, use it in vs2012 and plot the highcharts.
----------------Updated Question-------------
Below is the function I am trying to call in java-script where I want to evoke data from JSON format, but I am not able to call my function, below is my code
<script>
$(document).ready(function () {
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
series: [{}]
};
alert("outside");
$.getJSON('data.json', function (data) {
alert("INside");
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
</script>
and want to pass the data to the highcharts ,Since I am novice, any help will be greatly appreciated.
==============EDIT 2 =====================================
the Json file am trying to use for the data is in following format.
[
[1,12],
[2,5],
[3,18],
[4,13],
[5,7],
[6,4],
[7,9],
[8,10],
[9,15],
[10,22]
]
Thank You.
If JSON file is not rendering on the browser and your are getting 404 error then you might be facing the mime type handling problem, please refer the below link which resolves the issue,
getJSON method does not work
ASP.NET MVC Server Code:
namespace ABPMVCTest.Web.Controllers
{
[AbpMvcAuthorize]
public class HomeController : ABPMVCTestControllerBase
{
static Random _ran=new Random();
public ActionResult Index()
{
return View();
}
public ContentResult GetJsonResult()
{
var dataList = new List<ChartDataFormat>();
GetData(dataList, "总收入");
GetData(dataList, "投币收入");
GetData(dataList, "扫码充电收入");
GetData(dataList, "售线收入");
var dataJsonStr=JsonConvert.SerializeObject(dataList,new JsonSerializerSettings(){ContractResolver = new CamelCasePropertyNamesContractResolver()});
return Content(dataJsonStr);
}
private static List<ChartDataFormat> GetData(List<ChartDataFormat> dataList, string key)
{
var list = new List<int>();
for (int i = 0; i < 7; i++)
{
list.Add(_ran.Next(1, 3000));
}
dataList.Add(new ChartDataFormat
{
Name = key,
Data = list
});
return dataList;
}
}
class ChartDataFormat
{
public string Name { get; set; }
public List<int> Data { get; set; }
}
}
Client javascript Code:
$(function() {
Highcharts.setOptions({
lang: {
printChart: '打印图表',
downloadJPEG: '下载为JPEG图片',
downloadPDF: '下载为PDF',
downloadPNG: '下载为PNG图片',
downloadSVG: '下载为SVG矢量图',
months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
weekdays: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
shortMonths: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
}
});
var nowDate = new Date();
var option = {
chart: {
type: 'area'
},
title: {
text: '收入趋势图'
},
subtitle: {
text: '没有选择时间范围的话,默认显示当日/月前后3天/月的数据'
},
credits: {
enabled:false
},
xAxis: {
type: 'datetime',
tickmarkPlacement: 'on',
title: {
enabled: false
},
dateTimeLabelFormats: {
day: "%Y-%m-%d",
week: "%A",
month: "%Y-%m",
year: "%Y"
}
},
yAxis: {
title: {
text: '单位:元'
},
labels: {
formatter: function() {
return this.value;
}
}
},
tooltip: {
shared: true,
valueSuffix: ' 元',
dateTimeLabelFormats: {
day: "%Y-%m-%d,%A",
week: "%A开始, %Y-%m-%d",
month: "%Y-%m",
year: "%Y"
}
},
plotOptions: {
area: {
stacking: 'normal',
lineColor: '#666666',
lineWidth: 1,
marker: {
lineWidth: 1,
lineColor: '#666666'
}
},
series: {
pointStart:Date.UTC(nowDate.getFullYear(),nowDate.getMonth(),nowDate.getDate()-3) ,
pointInterval: 24 * 36e5 //一天
}
},
series: [{}]
}
var url = "/Home/GetJsonResult";
$.getJSON(url, function(data) {
option.series = data;
$('#container').highcharts(option);
});
});
Related
I'm using datatable.js, I have table in view and API returns JSON results. I have lots of rows and i want to bind them by each page.Is there any way that datatable do it for me? I read lots of documentation but I didn't find anything useful for API
API Controller
public IHttpActionResult Get(int id)
{
return Ok(_context.Students.OrderBy(c => c.id).Skip((id - 1) * 10).Take(10).ToList());
}
Here is my table config
<script>$(document).ready(function () {
var pageindex = 1;
var table = $("#staff").DataTable({
"processing": true,
"serverSide": true,
ajax: {
url: "/Api/staffs",
dataSrc: "",
data: {
id: pageindex,
},
},
columns: [
{
data: "stf_FirstName",
},
{
data: "stf_LastName",
},
{
data: "stf_Code",
}
]
});
table.on('page', function () {
Currentpagenum();
});
function Currentpagenum() {
var info = table.page.info();
pageindex = (info.page + 1);
}
});</script>
If there are lots of rows than server side processing should be used
Try this :
HTML :
<table id="tblGrid" class="table display nowrap" style="width:100%">
</table>
JS :
function SetGrid() {
$('#tblGrid').DataTable({
"proccessing": true,
"serverSide": true,
// server side
"ajax": {
url: "/api/YourController/Method",
type: 'POST',
"data": {
Param1: Value1
}
},
// if client side
//data: YourList, // Js Array
columns: [
{ data: 'Id' },
{ data: 'Name', title: "Name" },
...
...
{ title: "Actions"},
],
"columnDefs": [
{ targets: 0, visible: false,},
],
"ordering": false,
"lengthChange": false,
"pageLength": 10,
"bDestroy": true,
"oLanguage": {
"sEmptyTable": "No Record Found"
},
});
}
Sample C# :
public object YourMethod(Param1 Value1)
{
var start = int.Parse(HttpContext.Current.Request.Form["start"]);
var result = new {
draw = HttpContext.Current.Request.Form["draw"],
recordsTotal = YourList.Count,
recordsFiltered = YourList.Count,
data = YourList.Skip(start).Take(10).ToList()
};
return result;
}
I want to be able to return json object with a custom error/success message using the same line of code on post request: i have these two lines of code:
return Json(data);
return Json(new { f = "error" });
I want to be able display it in one line like this:
return Json(data, Json(new { f = "error" }));
I know i can't have multiple return statements in my code. but i want to return the data with message.
My ServerSide Code:
if (getId > 0)
{
var getList = appointmentRepository.GetAppointmentList(userId);
var data = Newtonsoft.Json.JsonConvert.SerializeObject(getList);
return Json(data);
return Json(new { s = "success" });
}
else
{
var getList = appointmentRepository.GetAppointmentList(userId);
var data = Newtonsoft.Json.JsonConvert.SerializeObject(getList);
return Json(data);
return Json(new { f = "error" });
}
My Ajax Fucntion:
<script type = "text/javascript">
$(document).ready(function () {
$('#tblAppointment').DataTable({
dom: 'Bfrtip',
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5'
]
});
var table = $("#tblAppointment").DataTable();
$("#saveButton").click(function () {
console.log("appDate:" + $('.datetimepicker').val());
$.ajax({
url: '/Appointment/InsertPatientAppointment/',
type: "POST",
data: JSON.stringify({
appointmentDate: $(".datetimepicker").val(),
patientRegNo: $("#patientRegNo").val(),
reasons: $("#reasons").val()
}),
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (_data) {
if (_data.f !== undefined) {
swal({
title: "Failed!",
text: _data.f, //"Ooops! something went wrong,
record not saved,
try again later ",
type: "info"
});
table.clear().draw();
//table.destroy();
// $("#viewReportBtn").prop("disabled", false);
return false;
} else {
swal({
title: "Success!",
text: _data.s, //"Appointment added successfully!",
type: "success"
});
}
$(".datetimepicker").val('');
$("#patientRegNo").val('');
$("#reasons").val('');
var arr = $.map(JSON.parse(_data), function (el) {
return
el
});
if (arr.length === 0) {
swal({
title: "No Record Found!",
text: _data.f, //"Your search returns an empty
result set !",
type: "info"
});
table.clear().draw();
return false;
}
table.clear();
table.destroy();
$('#tblAppointment').dataTable({
data: arr,
columns: [{
"data": "MatricRegNo"
},
{
"data": "PatientName"
},
{
"data": "EntryDate"
},
{
"data": "AppointmentDate"
},
{
"data": "Reasons"
},
{
"data": function (data, type, row, meta) {
return '<span class="fa fa-edit" data-
toggle = "modal"
data - target = "#modal-Edit" > < /span>';
}
}
],
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel',
{
extend: 'pdfHtml5',
orientation: 'Portriat',
pageSize: 'A4'
}
]
});
table = $("#tblAppointment").DataTable();
}
});
});
});
</script>
You can use this:
var data = Newtonsoft.Json.JsonConvert.SerializeObject(getList);
var returnData = new object[2];
returnData[0] = data;
returnData[1] = new { f = "error" };
return Json(returnData);
You can integrate the data object in your anonymous object which you are already returning:
return Json(new {data = data, f = "error"});
If you do it like this, you can access the data object in your ajax call like this:
success: function (_data) {
var returnedData = _data.data;
}
Which means you have to adjust your map method call where you are preparing the data array for the table. Instead of:
var arr = $.map(JSON.parse(_data), function (el) { return el });
call it with the data object _data.data:
var arr = $.map(JSON.parse(_data.data), function (el) { return el });
This should do the trick.
I would potentially approach in the following manner, extend the JsonResult to include a status code. This way you can dictate the level of success to the Ajax request.
public class JsonResultWithStatusCode : JsonResult
{
private readonly HttpStatusCode statusCode;
public JsonResultWithStatusCode(object data, HttpStatusCode statusCode)
{
Data = data;
this.statusCode = statusCode;
}
public override void ExecuteResult(ControllerContext context)
{
context.RequestContext.HttpContext.Response.StatusCode = (int)statusCode;
base.ExecuteResult(context);
}
}
Then inside your controller:
if(...)
{
var model = JsonConvert.SerializeObject(...);
return new JsonResultWithStatusCode(model, HttpStatusCode.Ok)
}
else
{
var model = new { error = "..." };
return new JsonResultWithStatusCode(model, HttpStatusCode.InternalServerError);
}
Then inside your Ajax you would be able to read the status code and then read the body.
.success: function(response) {
console.log(response.status); // Status Code (200 or 500 based on above)
console.log(response.data); // Our model based on above, one writing error the other actual model data.
}
All you would have to do would be read based on the server output.
I have a kendo grid in my application and i have added export to excel button to that kendo grid .
My question here is if select the small amount of data in kendo grid and when click on export button everything is working fine
but the problem is if select the large amount of data more than 1000 rows then the web page will become crash and it showing "Aw, Snap" Error
my environment : C#, Jquery, Kendo Grid
I have this code in my js
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
tableToExcel("table2excel");
it works fine when the data is small . but if the data is large more than 1000 it crashes the browser
I heard that Chrome can only handle HREF's that are roughly 2 million characters long. So can i handle this using Blob object ? if yes can somebody let me know how to use blob object in my case ?
Please help to resolve this issue .
It exports all data and custom selection using checkbox as well.
function excelExport() {
var exportAll = $('.selectrow').is(":checked");
var grid = $("#grid");
var rows = [{
cells: [
{ value: "column1" },
{ value: "column2" },
{ value: "column3" },
{ value: "column4" },
{ value: "column5" },
{ value: "column6" },
{ value: "column7" }
]
}];
if (exportAll) {
var dataDource = grid.getKendoGrid();
var trs = $("#grid").find('tr');
for (var i = 0; i < trs.length; i++) {
if ($(trs[i]).find(":checkbox").is(":checked")) {
var dataItem = dataDource.dataItem(trs[i]);
rows.push({
cells: [
{ value: dataItem.column1 },
{ value: dataItem.column2 },
{ value: dataItem.column3 },
{ value: dataItem.column4 },
{ value: dataItem.column5 },
{ value: dataItem.column6 },
{ value: dataItem.column7 }
]
})
}
}
}
else {
var dataSource = grid.data("kendoGrid").dataSource;
var trs = grid.find('tr');
for (var i = 1; i < dataSource._data.length; i++) {
var dataItem = dataSource._data[i];
rows.push({
cells: [
{ value: dataItem.column1 },
{ value: dataItem.column2 },
{ value: dataItem.column3 },
{ value: dataItem.column4 },
{ value: dataItem.column5 },
{ value: dataItem.column6 },
{ value: dataItem.column7 }
]
})
}
}
var workbook = new kendo.ooxml.Workbook({
sheets: [
{
columns: [
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true }
],
title: "Exported Data Result",
rows: rows
}
]
});
kendo.saveAs({ dataURI: workbook.toDataURL(), fileName: "ExportedData" });
}
I am trying to show a Pie Chart in my web application. Here is the data that was showing the Pie Chart in jquery.
var piedata = [
{ label: "Pending", data: 0 },
{ label: "In Progress", data: 65 },
{ label: "Cancelled", data: 15 },
{ label: "Submitted", data: 110 },
{ label: "Open", data: 60 },
{ label: "On Hold", data: 57 }
];
Here is the jquery Script to Show the Pie Chart
<script>
$(document).ready(function () {
var isPostBackObject = $("#hdnIsPostback");
alert(isPostBackObject.val());
if ($("#piechart").length) {
$.plot($("#piechart"), isPostBackObject.val(),
{
series: {
pie: {
show: true
}
},
grid: {
hoverable: true,
clickable: true
},
legend: {
show: false
}
});
function pieHover(event, pos, obj) {
if (!obj)
return;
percent = parseFloat(obj.series.percent).toFixed(2);
$("#hover").html('<span style="font-weight: bold; color: ' + obj.series.color + '">' + obj.series.label + ' (' + percent + '%)</span>');
}
$("#piechart").bind("plothover", pieHover);
}
});
</script>
Since this was in Jquery, so these are hard coded values. I have the status ifnormation in database that I want to set above. How do I set the data from code behind file so that I can show the Pie chart based on values from db.
I have tried to set like this
var data = new Dictionary<string, string>();
data.Add("Pending", "10");
data.Add("New", "40");
data.Add("Overdue", "50");
hdnIsPostback.Value = new JavaScriptSerializer().Serialize(data);
This code does show the Piechart but the labels like "Pending"/"New" dont show up in the Pie chart. Undefined appears instead. How do I do this?
You can use a normal C# array or IEnumerable..
You define a C# class;
public class PieModel {
public string label { get; set; }
public double data { get; set; }
}
And save the data to a list instead;
var data = new List<PieModel> {
new PieModel { label = "Pending", data = 10d }
new PieModel { label = "New", data = 40d }
new PieModel { label = "Overdue", data = 50d }
};
hdnIsPostback.Value = new JavaScriptSerializer().Serialize(data);
It is not tested code
With your updated answer you are going to need to parse the value of your textbox to JSON.. JSON.parse..
var isPostBackObject = $("#hdnIsPostback");
if ($("#piechart").length) {
$.plot($("#piechart"), JSON.parse(isPostBackObject.val()),
The JavaScriptSerializer will serialize your dictionary into an array of objects that contain Key and Value pairs ([{Key:"Pending", Value:"0"}...]) and that's definitely not the format you expect.
You need to project your dictionary into an array of objects containing label and data fields:
var pieData = data.Select(x => new
{
label = x.Key,
data = x.Value
}).ToArray();
Then serialize it to JSON:
hdnIsPostback.Value = new JavaScriptSerializer().Serialize(pieData);
The best equivalent IMO is the dynamic List as of C#4.0+ and anonymous types (objects)
var data=new List<dynamic>(){
new { label = "Pending", data = 10d },
new { label = "New", data = 40d },
new { label = "Overdue", data = 50d }
};
var serialised = new JavaScriptSerializer().Serialize(data);
I am trying the code of highstocks which is given below
<script type="text/javascript">
$(function () {
Highcharts.setOptions({
global: {
useUTC: false
}
});
// Create the chart
$('#container').highcharts('StockChart', {
chart: {
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = <%=chartData%>
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
rangeSelector: {
buttons: [{
count: 1,
type: 'minute',
text: '1M'
}, {
count: 5,
type: 'minute',
text: '5M'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 0
},
title: {
text: 'Sensor Data'
},
exporting: {
enabled: false
},
series: [{
name: 'Sensor Value',
data: (function () {
//generate an array of random data
var data = [], time = (new Date()).getTime(), i;
for (i = -999; i <= 0; i++) {
data.push([
time + i * 1000,
<%= chartData%>
]);
}
return data;
})()
}]
});
});
</script>
and displaying it in to the container
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto; width: 733px;"></div>
The code behind is
public string chartData
{
get;
set;
}
protected void Page_Load(object sender, EventArgs e)
{
GetData();
List<int> _data = new List<int>();
foreach (DataRow row in dt.Rows)
{
_data.Add((int)row["Id"]);
}
JavaScriptSerializer jss = new JavaScriptSerializer();
chartData = jss.Serialize(_data); //this make your list in jSON format like [88,99,10]
Response.Write(chartData);
}
private void GetData()
{
StringBuilder str = new StringBuilder();
SqlConnection con = new SqlConnection("Data Source=INBDQ2WK2LBCD2S\\SQLEXPRESS;Initial Catalog=MCAS;Integrated Security=SSPI");
SqlDataAdapter adp = new SqlDataAdapter("select top 1 Id from Monitoring order by Id desc ", con);
adp.Fill(dt);
}
Here I have created a JSON and I am transferring it to the javascript for highchart.
The problem I am having is that it is showing only one point. The values which are also updated in the database it is not updating in the chart.
What is wrong with it?
In your code I can see this:
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = <%=chartData%>;
series.addPoint([x, y], true, true);
}, 1000);
I guess, that chartData variable is where you have stored new point? At least you expect to have there. However your variable chartData is assigned in HTML once, after page is loaded from server. That you will update value on server, doesn't mean value get updated on client side.
I advice to use AJAX calls, for example: http://www.highcharts.com/studies/live-server.htm (see sources for code example).