Array equivalent of Jquery in c# - c#

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);

Related

How to pass JSON data from MVC4 to Flot without writing an adapter

I am generating data for Jquery flot in my MVC controller and want to use more sophisticated structure where I would be able to change colors for each bar etc..
to do this I need to pass data structure that looks following
{
label: "y = 3",
data: [[0, 3], [10, 3]]
}
I had no problem passing data when it was simple array by simply getting the data and shaping it like following
var data = topAgents.Select(agent => new List<object>
{
agent.User != null ? string.Format("{0}", agent.User).Replace("SAGANTGB\\", "") : null,
agent.Amount
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
and in javascript side:
function onAgentDataReceived(series) {
$("#agents").empty();
$.plot("#agents", [series], { bars: { show: true, barWidth: 0.6, align: "center" }, xaxis: { mode: "categories", tickLength: 0 } });
}
However now I can't seem to be able to shape data into such a structure that would fit what $.plot is expecting.
So far I have tried:
KeyValue pair:
var grouped = result.GroupBy(o => o.CREATE_USER_ID).Select(agent => new
{
data = new KeyValuePair<string,int>(
agent.Key != null ? string.Format("{0}", agent.Key).Replace("SAGANTGB\\", "") : null, agent.Count()
),
color = "yellow"
}).ToList();
Object with properties:
var grouped = result.GroupBy(o => o.CREATE_USER_ID).Select(agent => new
{
data = new { A=
agent.Key != null ? string.Format("{0}", agent.Key).Replace("SAGANTGB\\", "") : null, B = agent.Count()
},
color = "yellow"
}).ToList();
Name Value collection
var grouped = result.GroupBy(o => o.CREATE_USER_ID).Select(agent => new
{
data = new NameValueCollection
{{
agent.Key != null ? string.Format("{0}", agent.Key).Replace("SAGANTGB\\", "") : null, agent.Count().ToString()}
},
color = "yellow"
}).ToList();
Anonymous object array
var grouped = result.GroupBy(o => o.CREATE_USER_ID).Select(agent => new
{
data = new object[] { agent.Key != null ? string.Format("{0}", agent.Key).Replace("SAGANTGB\\", "") : null, agent.Count()},
color = "yellow"
}).ToList();
but none of them flied
IMHO simple data = new object { agent.Key, agent.Count()},
should work but it fails on build with: Error 16 Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access..
I could reshape the data in JS after retrieving it however would like to avoid this unnecessary step.
How do I pass data from MVC to javascript without having to reshape it on JS end?
After writing this question for 20 minutes, succeeded on next try
var grouped =
result.GroupBy(o => o.CREATE_USER_ID).Select(agent => new
{
data = new List<List<object>>
{
new List<object>
{
agent.Key != null ? string.Format("{0}", agent.Key).Replace("SAGANTGB\\", "") : null,
agent.Count()
}
},
color = "yellow"
}).ToList();
return Json(grouped, JsonRequestBehavior.AllowGet);
Apparently you need to double wrap it in list.
Forgot to mention there is no longer need to wrap in in array on JS side
$.ajax({
url: '/dashboard/Home/CancellationAgents/',
type: "GET",
dataType: "json",
success: onCancellationAgentsReceived
});
function onCancellationAgentsReceived(series) {
$("#agentcancellations").empty();
$.plot("#agentcancellations", series, {
bars: { show: true, barWidth: 0.7, align: "center" }, xaxis: {mode: "categories", tickLength: 0, position: "bottom"}});
}
Hope this saves you some time

export large amount of data to excel crashes

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" });
}

C# Linq Convert data to the right format for a chart

I am trying to get data to end up in the following format for my DOTNET.highcharts chart.
series: [{
name: 'Tokyo',
data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}, {
name: 'New York',
data: [83.6, 78.8, 98.5, 93.4, 106.0, 84.5, 105.0, 104.3, 91.2, 83.5, 106.6, 92.3]
I am unsure as to how I should do this. This is the Linq I use below to get data from my database.
var data = db.sp_chart_type();
List<string> x_Axis = new List<string>();
List<object[]> y_Axis = new List<object[]>();
foreach (var d in data)
{
x_Axis.Add(d.eis_code);
y_Axis.Add(new object[] { d.type, d.gcount });
}
var xArray = x_Axis.Distinct().ToArray();
render_Chart(xArray, y_Axis);
This outputs data like so
series: [{ data: [['a', 49], ['b', 3], ['a', 33], ['b', 0]
Would someone advise as to how I could get my data like the format posted? Or provide other advice if they have a better method than above.
Edit: render_Chart & highcharts clarification
protected void render_Chart(string[] xAxis, List<object[]> yAxis)
{
Highcharts chart = new Highcharts("chart")
.InitChart(new Chart
{
DefaultSeriesType = ChartTypes.Column
})
.SetTitle(new Title
{
Text = "Title"
})
.SetSubtitle(new Subtitle
{
Text = "Subtitle"
})
.SetXAxis(new XAxis
{
Categories = xAxis
})
.SetPlotOptions(new PlotOptions
{
Column = new PlotOptionsColumn
{
DataLabels = new PlotOptionsColumnDataLabels
{
Enabled = true,
Formatter = "function() { return this.point.y; }"
}
}
})
.SetLegend(new Legend
{
Enabled = false
})
.SetSeries(new Series
{
Data = new DotNet.Highcharts.Helpers.Data(yAxis.ToArray())
})
.SetCredits(new Credits
{
Enabled = false
});
ltrChart.Text = chart.ToHtmlString();
}
Thanks

Live HighChart not displaying 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).

how to import JSON data into VS2012 to plot highcharts

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);
});
});

Categories

Resources