Update command not firing datasource's update transport method - Kendo Grid - c#

Hi I am returning a data table from a stored procedure which is used to bind the grid. No Identity field is returned from that data table. in this scenario please help me out with firing 'update', 'destroy' and 'create'.
This is my controller method,
public JsonResult Employee_Read([DataSourceRequest]DataSourceRequest request)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["manualconn"].ConnectionString))
{
var command = new SqlCommand("usp_FetchUserDetails", con);
command.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(dt);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return Json(rows, JsonRequestBehavior.AllowGet);
}
// }
}
This is the part of my view:
<script type="text/javascript">
var grid = $("#grid").data("kendoGrid");
var Employee = kendo.data.Model.define({
id: "userDetailsId",
fields: {
"userDetailsId": { type: "number" },
"Name": { type: "string" },
"Department": { type: "string" },
"Role": { type: "string" },
"Email": { type: "string" },
}
});
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("Employee_Read", "UserSummary")',
dataType: "json",
cache: false,
type: 'GET',
//data: {
// test: $("#Names").val()
//}
},
destroy:
//function (e) {
{
url: '#Url.Action("Update_Details", "UserSummary")',
type: "POST",
// dataType: "json",
//data: {
// DAKy: $("#Names").val(),
// DIKy: $("#btntxt").val()
//}
},
create: {
url: '#Url.Action("Update_Details", "UserSummary")',
type: "POST",
// dataType: "json",
//cache: false,
//data: {
// AKy: $("#Names").val(),
// IKy: $("#btntxt").val()
//}
},
update:
{
url: '#Url.Action("Update_Details", "UserSummary")',
type : "POST"
//data: {
// AKy: $("#Names").val(),
// IKy: $("#btntxt").val()
// }
}
},
error: function (e) {
// handle error
alert("Status: " + e.status + "\n" + e.errorThrown);
},
pageSize: 5,
schema: {
model: {
id: "userDetailsId",
model: Employee
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
editable: "inline",
//toolbar: ["create", "save"],
autobind: true,
pageable: true,
columns: [
//{
// field: "userDetailsId",
// title: "userDetailsId",
// width: "50px",
//},
{
field: "Name",
title: "Name",
width: "75px",
template: "<input id='Name' type='text' value='#: Name #' readonly> </input>",
editable:false,
},
{
field: "Department",
title: "Department",
width: "50px",
editor: ddlFetchDepartments
},
{
field: "Role",
title: "Role",
width: "50px",
editor: ddlFetchRoles
},
{
field: "Email",
title: "Email",
width: "100px",
template: "<input type='text' id='Email' size='35' value='#:Email#' readonly> </input>",
editable:false,
},
{
command: ["edit", "destroy"], title: " ", width: "75px"
},
{ command: { text: "custom edit", click: showDetails },title: " ", width: "60px" }
],
});
function showDetails(e) {
e.preventDefault();
//debugger;
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
alert("View Details\n Name : " + dataItem.Name+"\nuserDetailsId : "+dataItem.userDetailsId);
#{
// ((MockProject.Controllers.UserSummaryController)this.ViewContext.Controller).Update_Details();
}
}
function ddlFetchDepartments(container, options) {
$('<input name="Departments" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
dataTextField: "deptName",
dataValueField: "deptId",
autoBind: false,
dataSource: new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("FetchDepartments", "UserSummary")',
type: 'GET',
dataType: "json"
},
schema: {
model: {
id: "deptId",
value: "deptName"
}
}
}
})
});
}
function ddlFetchRoles(container, options) {
$('<input name="Roles" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
dataTextField: "roleName",
dataValueField: "roleId",
autoBind: false,
dataSource: new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("FetchRoles", "UserSummary")',
type: 'GET',
dataType: "json"
},
schema: {
model: {
id: "roleId",
value: "roleName"
}
}
}
})
});
}
#*#{
((HomeController)this.ViewContext.Controller).Method1();
}*#
</script>
<br/>
<button type="button" id="btn_addUser" > Add User</button>
<input type="submit" style="visibility:hidden" name="btn_save" class="k-button k-button-icontext" id="btn_save" value="Save" onclick="saveDataToDb()" />
<script type="text/javascript">
function saveDataToDb() {
}
$('#btn_addUser').click(function () {
document.getElementById('btn_save').style.visibility = "visible";
$('#grid').data('kendoGrid').addRow();
});
function onEdit(e) {
//Custom logic to default value
var name = $("#AddSingleSuppliment").text();
// If addition
if (e.model.isNew()) {
//set field
e.model.set("Name", name); // Name: grid field to set
}
}
</script>
<script>
$(document).ready(function () {
$("#btn_addUser").kendoButton({
spriteCssClass: "k-icon iconplus"
});
});
</script>
<style scoped>
.k-button .k-image {
height: 16px;
}
.demo-section {
width: 500px;
}
.iconplus {
background-image: url("../content/icons/plus.png");
background-size: contain;
/*background-position: 0 -64px;
align-content: flex-start;
align-self: auto;*/
}
</style>

Related

Bind Json data to Echart

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>

A public action method 'xyz' was not found on controller

I have Kendo Grid in my view. I have specified read , edit and delete each as of type HTTPPOST. But when I try to edit or delete i get an error that : "A public action method 'UpdateDetails' was not found on controller 'Nop.Plugin.Misc.CategoryWiseShipping.Controllers.ShippingChargeController'." for update Action and similarly one other for delete option.
Interesting thing is that it works fine on my local machine but throws error when published to server
I have searched extensivelly on google but couldn't find the reason as to why it is happening.
This is the controller actionMethod
[HttpPost]
public ActionResult UpdateDetails(ShippingChargeModel shippingChargeModel)
{
if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts))
return AccessDeniedView();
if (shippingChargeModel.SchoolEmail == null)
{
ErrorNotification(" Email can not be null !!", true);
return RedirectToAction("AddShippingCharge", "ShippingCharge");
}
if (shippingChargeModel.SaleStartDate == null)
{
ErrorNotification(" Sale start date can not be null !!", true);
return RedirectToAction("AddShippingCharge", "ShippingCharge");
}
if (shippingChargeModel.SaleEndDate == null)
{
ErrorNotification(" Sale end date can not be null !!", true);
return RedirectToAction("AddShippingCharge", "ShippingCharge");
}
if (shippingChargeModel.SaleEndDate < shippingChargeModel.SaleStartDate)
{
ErrorNotification(" Sale start date should be less than sale end date!!", true);
return RedirectToAction("AddShippingCharge", "ShippingCharge");
}
var modelFromDb = _catShippingService.GetRecord(shippingChargeModel.Id);
modelFromDb.SaleEndDate = shippingChargeModel.SaleEndDate.Value.AddMinutes(330);
modelFromDb.SaleStartDate = shippingChargeModel.SaleStartDate.Value.AddMinutes(330);
modelFromDb.SchoolEmail = shippingChargeModel.SchoolEmail;
modelFromDb.ShippingCharge = shippingChargeModel.ShippingCharge;
modelFromDb.ModifyDate = DateTime.Now;
_catShippingService.Update(modelFromDb);
return new NullJsonResult();
}
This is my Kendo Grid :
function loadKendo() {
var dataNew = {};
$("#shippingCharge-grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("GetDetails", "ShippingCharge"))",
type: "POST",
dataType: "json",
},
update: {
url: "#Html.Raw(Url.Action("UpdateDetails", "ShippingCharge"))",
type: "POST",
dataType: "json",
//data: addAntiForgeryToken
},
destroy: {
url: "#Html.Raw(Url.Action("DeleteDetails", "ShippingCharge"))",
type: "POST",
dataType: "json",
}
,
parameterMap: function (data, operation) {
if (operation === "update") {
dataNew.Id = data.Id;
dataNew.CategoryId = data.CategoryId;
dataNew.ShippingCharge = data.ShippingCharge;
dataNew.SaleStartDate = stringToTimestamp(data.SaleStartDate.toUTCString());
dataNew.SaleEndDate = stringToTimestamp(data.SaleEndDate.toUTCString());
dataNew.SchoolEmail = data.SchoolEmail;
return { ShippingChargeModel: dataNew };
}
return data;
}
},
schema: {
data: "Data",
total: "Total",
errors: "Errors",
model: {
id: "Id",
fields: {
//ProductId: { editable: false, type: "number" },
CategoryId: { editable: false, type: "string" },
CategoryName: { editable: false, type: "string" },
ShippingCharge: { editable: true, type: "number" },
SaleStartDate: { editable: true, type: "date", format: "{0:dd/MMM/yyyy HH:mm}"},
SaleEndDate: { editable: true, type: "date", format: "{0:dd/MMM/yyyy HH:mm}"},
SchoolEmail: { editable:true, type: "string" }
}
}
},
requestEnd: function (e) {
if (e.type == "update") {
this.read();
}
if (e.type == "cancel") {
this.cancelChanges();
}
},
error: function (e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
pageable: {
refresh: true,
numeric: false,
previousNext: false,
info: false,
pageSizes: [#(gridPageSizes)]
},
editable: {
confirmation: "#T("Admin.Common.DeleteConfirmation")",
mode: "inline"
},
scrollable: false,
columns: [
{
field: "CategoryName",
title: "CategoryName",
width: 300
},
{
field: "ShippingCharge",
title: "Shipping Charge",
width: 100,
encoded: false
}
,
{
field: "SchoolEmail",
title: "Email",
width: 200,
encoded: false
}
,
{
field: "SaleStartDate",
title: "Sale Start Date",
width: 200,
encoded: false,
type: "datetime",
format: "{0:dd/MMM/yyyy HH:mm}",
template: "#= kendo.toString(kendo.parseDate(SaleStartDate, 'yyyy-MM-dd'), 'dd/MMM/yyyy') #",
editor: dateTimeEditor
},
{
field: "SaleEndDate",
title: "Sale End Date",
width: 200,
encoded: false,
type: "datetime",
format: "{0:dd/MMM/yyyy HH:mm}",
template: "#= kendo.toString(kendo.parseDate(SaleEndDate, 'yyyy-MM-dd'), 'dd/MMM/yyyy') #",
editor: dateTimeEditor
}, {
command: [
{
name: "edit",
text: {
edit: "#T("Admin.Common.Edit")",
update: "#T("Admin.Common.Update")",
cancel: "#T("Admin.Common.Cancel")"
}
}
, {
name: "destroy",
text: "#T("Admin.Common.Delete")"
}
],
width: 200
}
]
});
}
Please help me out. Any sort of insight will do ...

Telerik Kendo Grid editing inline with kendo treeview editor template

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>

Kendo Grid update event not firing up

I am using MVC4 ASP.NET and trying to create a Kendo Grid where I can edit data inline. I am connecting to a local database imported into Visual Studio using the Entity Framework. I followed the sample example on Kendos web page from here: http://demos.telerik.com/kendo-ui/grid/editing-inline Here is my View
Edit
When I click on the Update button after modifying an existing record in the Grid, it is not firing up in my Controller UpdateAsset method. I have also added an alert method in the Views update method and have not received the dialog box.
File code:
#{
ViewBag.Title = "Manage Assets";
}
<h2>ManageAssets</h2>
<div id="grid"></div>
<div>
<form style="background-color:#E6E6FA">
Switch:<input type="number" id="switch_txt" /><br />
Port:<input type="text" id="port_txt" /><br />
Name:<input type="text" id="name_txt" /><br />
Connection:<input type="text" id="connection_txt" /><br />
Interface:<input type="text" id="ifc_txt" /><br />
</form>
</div>
<div>
#*<input type="text" id="switchTxt" />*# #*This is Justins original code (JOC) *#
<button onclick="onSave()">Save</button><br />
</div>
<script>
var selectedRow = {};
var crudServiceBaseUrl = "/Asset";
$(document).ready(function () {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/GetAssets",
dataType: "json",
contentType: "application/json"
},
update: {
url: crudServiceBaseUrl + "/UpdateAsset",
dataType: "json",
type: "POST",
contentType: "application/json"
},
destroy: {
url: crudServiceBaseUrl + "/Destroy",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
pageSize: 20,
autoSync: true,
schema: {
model: {
id: "Gid",
fields: {
Switch: { type: "number", editable: true, nullable: true, validation: { required: true, min: 1 } },
Port: { type: "string", editable: true, nullable: true },
Name: { type: "string" },
Connection: { type: "string" },
Interface: { type: "string" },
ConnectionUser: { type: "string" },
ConnectionDate: { type: "string" }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 550,
selectable: true,
change: function () {
selectedRow = {
mySwitch: this.dataItem(this.select()).Switch,
myPort: this.dataItem(this.select()).Port,
myName: this.dataItem(this.select()).Name,
myConnection: this.dataItem(this.select()).Connection,
myInterface: this.dataItem(this.select()).Interface
};
alert(selectedRow['mySwitch']);
},
columns: [
{ field: "Switch", title: "Switch", format: "{0:n}", width: "120px" },
{ field: "Port", title: "Port" },
{ field: "Name", title: "Name" },
{ field: "Connection", title: "Connection" },
{ field: "Interface", title: "Interface" },
//{ command: ["edit", "destroy"], title: " ", width: "250px" }],
{ command: [
{
name: "edit",
//click: function(e) {
// alert("you just clicked edit");
//}
},
{ name: "destroy"}
]}],
editable: "inline"
});
});
// when the Save button is pressed this function is called
// the function creates the values for the table columns
function onSave() {
var myJSONObject = {
//switchTxt is coming from the text field div
asset_sw: $("#switch_txt").val(),
asset_port: $("#port_txt").val(),
asset_name: $("#name_txt").val(),
asset_conn: $("#connection_txt").val(),
asset_ifc: $("#ifc_txt").val()
};
//alert(myJSONObject);
$.ajax({
url: crudServiceBaseUrl + "/CreateAsset",
dataType: "json",
type: "POST",
data: myJSONObject, // here we pass the json object that contains all of our data
success: function (result) {
if (result.success == true)
{
alert(result.success);
alert('success');
$('#grid').data('kendoGrid').dataSource.read();
$('#grid').data('kendoGrid').refresh();
}
else {
alert(result.success);
alert('fail success');
}
},
error: function (result) {
alert(result);
alert('fail')
}
});
}
</script>

Binding json result in highcharts for asp.net mvc 4

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

Categories