net mvc4 c# razor project i want to implement dotnet highcharts.For that i have created a jsonresult function to get the data from datatable and a cshtml file to render the file.
Here my issue is that
1. i dont how to pass the data from json to view
2. how to display the result for x axis and series in highcharts.
Am beginner in asp.net mvc 4 and Highcharts..
cshtml
enter code here
<script type="text/javascript">
$(function () {
debugger;
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Audience Live Data'
},
subtitle: {
text: 'Mainadv'
},
xAxis: {
categories: [mySeries]
},
yAxis: {
min: 0,
title: {
text: 'Count'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Home',
data: [{ data: data }]
}, {
name: 'Category',
data: [{ data: data }]
}, {
name: 'Product',
data: [{ data: data }]
}, {
name: 'Basket',
data: [{ data: data }]
},{
name: 'Checkout',
data: [{ data: data }]
}]
});
});
</script>
Script file
<script type="text/javascript">
// the button action
debugger;
var url = "/AudienceLive/GetAudLiveChartData/";
$.ajax({
url: url,
cache: false,
Type: 'POST',
success: function (myData) {
var mySeries = [];
for (var i =0; i < myData.length; i++) {
mySeries.push([myData[i]]);
}
var chart = $('#container').highcharts();
chart.series[0].setData(mySeries);
// chart.series[0].pointStart=;
}, error: function (response) {
alert("error : " + response);
}
});
</script>
JsonResult Function
public JsonResult GetAudLiveChartData()
{
AudienceLiveRepo objlive=new AudienceLiveRepo ();
List<string> test=new List<string>();
DataTable dt = objlive.GetTable();
if(dt!=null)
{
if(dt.Rows.Count>0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
test.Add(Convert.ToString(dt.Rows[i][0]));
test.Add(Convert.ToString(dt.Rows[i][1]));
test.Add(Convert.ToString(dt.Rows[i][2]));
test.Add(Convert.ToString(dt.Rows[i][3]));
test.Add(Convert.ToString(dt.Rows[i][4]));
test.Add(Convert.ToString(dt.Rows[i][5]));
}
}
}
objlive = null;
return Json(test, JsonRequestBehavior.AllowGet);
}
View cshtml
$(document).ready(function () {
$.ajax({
url: "/home/ChartData",
type: 'POST',
dataType: 'json'
}).success(function (dataChart) {
var Xaxis = [];//skapa tre olika array
var dataseries = [];
for (var i = 0; i < dataChart.length; i++) {
var items = dataChart[i];
var XcategoreisItem = items.id;
var seriesData = items;
Xaxis.push(XcategoreisItem);
dataseries.push(seriesData);
console.log(dataseries);
}
getchart(Xaxis, dataseries);
}).error(function (er, xhr, e) {
console.log("Error: ", er, xhr, e);
})
});
function getchart(Xaxis, dataseries) {
$('#container').highcharts({
chart: {
type: 'line',
zoomType: 'xy',
panning: true,
panKey: 'shift'
},
title: {
text: 'Zooming and panning'
},
subtitle: {
text: 'Click and drag to zoom in. Hold down shift key to pan.'
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
format: '{y}%',
}
}
},
xAxis: {
categories: Xaxis
},
yAxis: {
title: {
text: 'Y axis text'
},
series: [{
name: 'Id',
data: dataseries
}]
});
};
HomeController
public ActionResult ChartData()
{
TbChart db = new TbChart();
var TbChartData = db.getYaxis();
return this.Json(TbChartData, JsonRequestBehavior.AllowGet);
}
Related
am trying to bind data from Database to Echart, My query returns the following value:
Transaction Iteration1
Init----------------- 0.02
Login ------------- 2.29
App --------------- 6.08
Up --------------- 4.88
Select ----------- 3.46
Log ---------------- 0.26
The Iteration column increases for example if i select two iteration, i will get 3 column that is Transaction---- Iteration1 ----- Iteration2
My query is running fine.
My json format:
data[ { Transaction:init, iteration:0.02 }, {
Transaction:Login,iteration1:2.29 }, { Transaction:App,
iteration1:6.08 }, { Transaction:Up, iteration1:4.88 }, {
Transaction:select, iteration1:3.46 }, {Transaction:Log,
iteration1:0.26 } ]
var myChart = echarts.init(document.getElementById('main'));
var params = {
runIds: '1'
};
$.ajax({
url: transactionUrl,
type: 'POST',
dataType: 'JSON',
contentType: 'application/json;',
data: JSON.stringify(params),
beforeSend: function () {
},
success: function (d) {
var seriesHeader = [];
if (seriesHeader.length === 0) {
seriesHeader.push('Transaction');
for (var key in d[0]) {
if (d[0].hasOwnProperty(key)) {
if (key !== 'Transaction') {
seriesHeader.push(key);
}
}
}
}
$.each(d, function (i, item) {
var count = 0;
while (count < seriesHeader.length) {
count += 1;
}
});
var option = {
title: {
//text: 'ECharts entry example'
},
tooltip: {},
legend: {
data: seriesHeader
},
xAxis: {
data: ???
},
yAxis: {},
series: [{
name: seriesHeader[1],
type: 'bar',
data: ??
}
]
};
// use configuration item and data specified to show chart
myChart.setOption(option);
},
error: function () {
}
});
Am a bit confuse how to pass the data to the Echart. Am help will be most welcome.
Please check this demo, assuming there are 2 Iteration.
Is this you want?
let echartsObj = echarts.init(document.querySelector('#canvas'));
let d = [{
Transaction: 'init',
iteration1: 0.02,
iteration2: 2.02,
}, {
Transaction: 'Login',
iteration1: 2.29,
iteration2: 0.52,
}, {
Transaction: 'App',
iteration1: 6.08,
iteration2: 3.53,
}, {
Transaction: 'Up',
iteration1: 4.88,
iteration2: 5.32,
}, {
Transaction: 'select',
iteration1: 3.46,
iteration2: 2.11,
}, {
Transaction: 'Log',
iteration1: 0.26,
iteration2: 1.02,
}]
let seriesHeader = d.map(item => item.Transaction)
let datas = [];
Object.keys(d[0]).forEach(key => {
if (key !== 'Transaction') {
datas.push({
name: key,
type: 'bar',
data: d.map(item => item[key])
})
}
})
option = {
xAxis: {
type: 'category',
data: seriesHeader
},
yAxis: {
type: 'value'
},
legend: {
data: datas.map(item => item.name)
},
series: datas
};
echartsObj.setOption(option)
<html>
<header>
<script src="https://cdn.bootcss.com/echarts/4.1.0.rc2/echarts-en.min.js"></script>
</header>
<body>
<div id="canvas" style="width: 100%; height: 200px">
</div>
</body>
</html>
I have a kendo grid that is edited inline. One of the fields should be edited selecting an element from a list, but the list must have a hierarchical structure (would be nice be able of filter that list). I was thinking in use a kendo treeview as editor for that field but I haven't found any way to accomplish this. I tried make a custom editor template (using columns.Bound(s => s.FieldId).EditorTemplateName("_TreeEditorTemplate")) that render the treeview, but the treeview is not an input and is not selectable. I also thinked in make an editor that use a kendo dropdownlist with the tree inside but this is no currently supported by kendo. Any ideas???
Have you looked at the sample on the Kendo site: https://docs.telerik.com/kendo-ui/controls/data-management/grid/how-to/Editing/use-treeview-as-grid-editor
<div id="example">
<div id="grid"></div>
<script>
$(document).ready(function () {
var crudServiceBaseUrl = "//demos.telerik.com/kendo-ui/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
ProductName: { validation: { required: true } },
UnitPrice: { type: "number", validation: { required: true, min: 1 } },
Discontinued: { type: "boolean" },
UnitsInStock: { type: "number", validation: { min: 0, required: true } }
},
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
edit: function (e) {
//checking if a cell from the Test column is opened for editing
var dummyInput = e.container.find("input[name='test']");
if (dummyInput.length > 0) {
var treeView = $(e.container).find(".treeViewEditor").data("kendoTreeView");
var originalItem = treeView.findByText(dummyInput.val());
if (originalItem != null) {
// Select the item based on the field value
treeView.select(originalItem);
}
}
},
navigatable: true,
pageable: true,
height: 550,
toolbar: ["create", "save", "cancel"],
columns: [
"ProductName",
{
field: "test", title: "Test", width: 120,
editor: function (container, options) {
var input = $("<input class='tveInput'/>");
input.attr("name", options.field);
var tvDiv = $("<div class='treeViewEditor'></div>");
$(tvDiv).kendoTreeView({
animation: false,
dataSource: [
{
text: "foo1"
},
{
text: "foo2",
items: [
{ text: "bar" },
{ text: "bar1" },
{ text: "bar2" }
]
}
]
});
var treeView = $(tvDiv).data("kendoTreeView");
$(tvDiv).find(".k-in").mousedown(function (e) {
var clickedNode = $(e.toElement).closest("[role=treeitem]");
var dataItem = treeView.dataItem(clickedNode);
var dummyInput = clickedNode.closest("[role=gridcell]").find("input[name='test']");
dummyInput.val(dataItem.text);
dummyInput.trigger("change");
});
tvDiv.appendTo(container);
input.appendTo(container);
}
},
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: 120 },
{ field: "UnitsInStock", title: "Units In Stock", width: 120 },
{ field: "Discontinued", width: 120 },
{ command: "destroy", title: " ", width: 150 }],
editable: true
});
});
</script>
</div>
<style>
.tveInput {
display: none;
}
</style>
I can generate a Pie Chart Just like the picture by using the code below
<script>
var pieChartData = [
{ label: "Data 1", data: 16, color: "#62cb31", },
{ label: "Data 2", data: 6, color: "#A4E585", },
{ label: "Data 3", data: 22, color: "#368410", },
{ label: "Data 4", data: 32, color: "#8DE563", }
];
var pieChartOptions = {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true
},
tooltip: true,
tooltipOpts: {
content: "%p.0%, %s", // show percentages, rounding to 2 decimal places
shifts: {
x: 20,
y: 0
},
defaultTheme: false
}
};
$.plot($("#_ByRegion"), pieChartData, pieChartOptions);
</script>
Now what I want to do is to generate the var data = [] dynamically from Controller. How to do this? Also the data is from the Database.
By Combining Pranav Patel and Ghanshyam Singh answers
I was able able to reach the desired output
Model
public class GenderPieChart_Model
{
public string GenderDesc { get; set; }
public int GenderID { get; set; }
}
Controller
public JsonResult Gender()
{
Dashboard_Layer data = new Dashboard_Layer();
var lst = data.Gender();
return Json(lst, JsonRequestBehavior.AllowGet);
}
Business Layer
public IEnumerable<GenderPieChart_Model> Gender()
{
List<GenderPieChart_Model> data = new List<GenderPieChart_Model>();
using (SqlConnection con = new SqlConnection(Connection.MyConn()))
{
SqlCommand com = new SqlCommand("dbo.sp_Project_DashBoard 4", con);
con.Open();
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
GenderPieChart_Model value = new GenderPieChart_Model();
value.GenderDesc = Convert.ToString(reader.GetValue(0));
value.GenderID = Convert.ToInt32(reader.GetValue(1));
data.Add(value);
}
}
return data;
}
View
<div class="flot-chart-content" id="_ByGender" style="height: 150px"></div>
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "#Url.Action("Gender", "Dashboard")",
content: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var myData = data;
var pieChartData = [];
$.each(data, function (i,v) {
pieChartData.push({ label: v.GenderDesc, data: v.GenderID, color: "#62cb31", });
})
var pieChartOptions = {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true
},
tooltip: true,
tooltipOpts: {
content: "%p.0%, %s", // show percentages, rounding to 2 decimal places
shifts: {
x: 20,
y: 0
},
defaultTheme: false
}
};
$.plot($("#_ByGender"), pieChartData, pieChartOptions);
}
})
});
</script>
you can call when your controller on ready event and after getting data (returned Json from your controller) can process further. You can try like below
<script>
$(document).ready(function(){
$.ajax({
type: "POST", //GET or POST
url: "<YOUR URL>",
data: "<YOUR PARAMETER IF NEEDED>",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){ //data is your json returned from controller
var myData = JSON.parse(data);
//create your 'pieChartData' from object 'myData'
//pieChartData =
var pieChartOptions = {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true
},
tooltip: true,
tooltipOpts: {
content: "%p.0%, %s", // show percentages, rounding to 2 decimal places
shifts: {
x: 20,
y: 0
},
defaultTheme: false
}
};
$.plot($("#_ByRegion"), pieChartData, pieChartOptions);
}
});
});
</script>
Its simple just return Json from your controller:
first create a model class for the properties
public class Chart
{
public string label{get;set;}
public string data{get;set;}
public string color{get;set;}
}
MVC action method:-
public JsonResult Chart()
{
List<Chart> chartList=new List();
// Code to fetch Data in List chartList
return Json(chartList,JsonRequestBehaviour.AllowGet);
}
Ajax Call:-
<script>
$(document).ready(function(){
$.ajax({
type: "POST", //GET or POST
url: "/Controller/Chart",
data: "<YOUR PARAMETER IF NEEDED>",
dataType: "json",
success: function(data){
$.each(data,function(i,index){
// Code to plot Chart here
});
}
});
});
</script>
i want to send data from kendo grid to sql database, here is my javascript view model code:
document.onreadystatechange = function () {
var viewModel = kendo.observable({
products: new kendo.data.DataSource({
schema: {
//data:"Data",
total: "Count",
model: {
Id: "Id",
fields: {
Id: { editable: true, type: "int" },
ShortName: { editable:true, type: "string" },
FullName: { editable: true, type: "string" },
ContactPerson: { editable: true, type: "string" },
CurrentCurrencyCode: { editable: true, type: "int" },
Adress1: { editable: true, type: "string" },
CompanyState: { editable: true, type: "string" },
CompanyCity: { editable: true, type: "string" },
CompanyCountry: { editable: true, type: "string" },
ZipPostCode: { editable: true, type: "string" },
TelArea: { editable: true, type: "string" }
}
}
},
batch: true,
transport: {
read: {
url: "/api/Companies/GetAllCompanies",
dataType: "json"
},
create:{
url: "/api/Companies/SaveDefCompny", // here is a correct api url, which i want to call
dataType: "json"
},
destroy: {
url: "/api/Companies/Delete",
dataType: "json"
},
parameterMap: function (data, operation) {
if (operation !== "read" && data) {
return kendo.stringify(data) ;
}
}
}
})
});
kendo.bind(document.getElementById("example"), viewModel);
}
Here is my controller code to post data to database but its is not calling by clicking create or update button what the problem with my grid or controller call?
[HttpPost]
public void SaveDefCompny(IEnumerable<DefCompanyDTO> DfCmpny1)
{
var result = new List<DefCompany>();
using (var data = new RPDBEntities())
{
foreach (var productViewModel in DfCmpny1)
{
var product = new DefCompany
{
Id = productViewModel.Id,
CurrentCurrencyCode = productViewModel.CurrentCurrencyCode,
ShortName= productViewModel.ShortName,
FullName= productViewModel.FullName,
ContactPerson= productViewModel.ContactPerson,
Address1= productViewModel.Address1,
CompanyCity= productViewModel.CompanyCity,
CompanyState= productViewModel.CompanyState,
CompanyCountry= productViewModel.CompanyCountry,
ZipPostCode= productViewModel.ZipPostCode,
TelArea= productViewModel.TelArea
};
result.Add(product);
data.DefCompanies.Add(product);
};
data.SaveChanges();
}
}
the url is correct but it doesnot called even while debugging cursor not goes to url but grid reads all values and display in it
As you are going to post data type: "POST" is missing in create method.
And also check posting data.models instead of data
Is there a way to set the models value on a page load. Because i need it to populate a schema with model values. and i tried a document.ready ajax call to get the model but it tells me that the model has no value before the ajax call even happens.
here is the code and you can see how im trying to populate the schema but it wont hit the functions
<script src="#Url.Content("~/Scripts/jquery-1.7.1.min.js")"> </script>
<script src="#Url.Content("~/Scripts/kendo/kendo.all.min.js")"></script>
<script>
$(document).ready(function () {
$.ajax({
url: '/Team/Calendar/PopulateCalendar/',
type: "POST",
data: $(this).serialize(),
});
});
$(function () {
$("#scheduler").kendoScheduler({
date: new Date("2013/6/13"),
startTime: new Date("2013/6/13 07:00 AM"),
height: 600,
views: [
"day",
{ type: "week", selected: true },
"month",
"agenda"
],
timezone: "Etc/UTC",
dataSource: {
batch: true,
transport: {
read: {
url: "/Team/Calendar/PopulateCalendar/",
dataType: "json"
},
update: {
url: "http://demos.kendoui.com/service/tasks/update",
dataType: "jsonp"
},
create: {
url: "http://demos.kendoui.com/service/tasks/create",
dataType: "jsonp"
},
destroy: {
url: "http://demos.kendoui.com/service/tasks/destroy",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
schema: {
model: {
id: "taskId",
fields: {
taskId: { from: "#Model.CalendarItems.Select(calendar=> calendar.TaskId)", type: "number" },
title: { from: "#Model.CalendarItems.Select(calendar=> calendar.Title)", defaultValue: "No title", validation: { required: true } },
start: { type: "date", from: "#Model.CalendarItems.Select(calendar => calendar.Start)" },
end: { type: "date", from: "#Model.CalendarItems.Select(calendar => calendar.End)" },
startTimezone: { from: "#Model.CalendarItems.Select(calendar => calendar.StartTimezone)" },
endTimezone: { from: "#Model.CalendarItems.Select(calendar => calendar.EndTimezone)" },
description: { from: "#Model.CalendarItems.Select(calendar => calendar.Description)" },
recurrenceId: { from: "#Model.CalendarItems.Select(calendar => calendar.RecurrenceId)" },
recurrenceRule: { from: "#Model.CalendarItems.Select(calendar => calendar.RecurrenceRule)" },
recurrenceException: { from: "#Model.CalendarItems.Select(calendar => calendar.RecurrenceException)" },
ownerId: { from: "OwnerID", defaultValue: 1 },
isAllDay: { type: "boolean", from: "#Model.CalendarItems.Select(calendar => calendar.IsAllDay)" }
}
}
},
filter: {
logic: "or",
filters: [
{ field: "ownerId", operator: "eq", value: 1 },
{ field: "ownerId", operator: "eq", value: 2 }
]
}
},
resources: [
{
field: "ownerId",
title: "Owner",
dataSource: [
{ text: "Alex", value: 1, color: "#f8a398" },
{ text: "Bob", value: 2, color: "#51a0ed" },
{ text: "Charlie", value: 3, color: "#56ca85" }
]
}
]
});
I think you are using ASPNET MVC with Razor, you should be able to set your model via Scriplet into the javascript.