Using Chart JS in Asp.net MVC - json

I have a table having no of files and their month. i want to show line chart for progress of every month. but i am not able to show the data in the chart,
in console.log date is also not in the required form. how should i put month names which are generated from the sql query on label fields and and every month counting of file on the data
DataSet ds = dbop.GetViews();
List<ListReg> list = new List<ListReg>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
list.Add(new ListReg
{
eFile_registered = Convert.ToInt32(dr["eFile_registered"]),
eFile_Month = Convert.ToDateTime(dr["eFile_Month"]).ToString()
});
}
return Json(list, JsonRequestBehavior.AllowGet);`
//model
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/test/LineChart",
method: 'GET',
dataType: "JSON",
success: function (dr) {
console.log(dr);
var month=dr[0];
var count=dr[1];
var ctx = document.getElementById("canvas").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
height: "230px",
width: "300px",
responsive: false,
animation: false,
legend: { position: 'bottom' },
data: {
//labels: ["M", "T", "W", "T", "F", "S", "S"],
labels: month,
datasets: [{
label: 'Monthly Expenses',
data: count,
backgroundColor: "rgb(66, 134, 244)"
}]
}, options: {
events: ['click'],
scaleShowValues: true,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
ticks: {
autoSkip: false
}
}]
}
}
});
},
"error": function (list) {
alert("Some Error Occured!");
}
});
})

Related

Kendo spreadsheet is not binding first time using json

I have a kendo spread sheet which is not loading first time in browser after refreshing it will works. I already searched lots of in google but unable to find any solutions.Please help me how to fixed that issue. I am using asp.net mvc.
my spread sheet code is below
var customVal = $("#customInput").data("value");
var CellCount = $('#sessionDivCount').attr('data-id');
var headercount = '1';
var displayCount = Number(CellCount) + Number(headercount);
$(function () {
var shouldPopulateHeader = true;
var dataSource = new kendo.data.DataSource({
requestEnd: function (e) {
setTimeout(function (e) {
if (shouldPopulateHeader) {
shouldPopulateHeader = false;
var spreadsheet = $("#spreadsheet").data("kendoSpreadsheet");
var sheet = spreadsheet.activeSheet();
// Change the default headers for the first and the second column
sheet.batch(function () {
sheet.range("A1").value("Order ID");
sheet.range("D1").value("Check/Receipt/Reference/Confirmation Number");
sheet.range("E1").value("Date Check Was Made Made/Payment Was Maid");
sheet.range("F1").value("Agent Payment Confirmation");
sheet.range("G1").value("Estimated payment Arrival Date");
sheet.range("A1:A16384 ").enable(false);
sheet.range("A2:A16384 ").textAlign = "center";
sheet.range("B1:B16384 ").enable(false);
var range = sheet.range("A2:A16384"); // 2x2 cell range
range.bold = true;
range.textAlign = "center";
range.color("green");
var range1 = sheet.range("B2:B16384"); // 2x2 cell range
range1.bold = true;
range1
range1.textAlign = "center";
range1.color("black");
range1.defaultValue = null;
sheet.range("c2").textAlign = "center";
}, { recalc: true });
}
}, 0);
},
transport: {
read: onRead,
submit: onSubmit
},
batch: true,
change: function () {
$("#cancel, #save").toggleClass("k-state-disabled", !this.hasChanges());
},
schema: {
model: {
OrderID: "OrderID",
fields: {
OrderID: {
type: "number",
defaultValue: null
},
PO: {
type: "string",
defaultValue: null
},
Method: {
type: "string",
},
Check_Receipt_Refernce_confirmation_Number: {
type: "string"
},
DateCheck_Was_Mailed_Payment_Was_Made: {
type: "date"
},
Agent_Payment_Confirmation: {
type: "string"
},
Estimated_Payment_Arrival_Date: {
type: "date"
},
}
}
}
});
$("#spreadsheet").kendoSpreadsheet({
columns: 7,
rows: displayCount,
toolbar: true,
sheetsbar: false,
sheets: [{
name: "Products",
dataSource: dataSource,
rows: [{
height: 20,
cells: [
{
value: "Order ID",
bold: "true",
background: "#9c27b0",
textAlign: "center",
color: "white",
hidden: true,
enable: false
}, {
bold: "true",
background: "#9c27b0",
textAlign: "center",
color: "white",
enable: false
}, {
bold: "true",
background: "#9c27b0",
textAlign: "center",
color: "white",
enable: false
}, {
bold: "true",
background: "#9c27b0",
textAlign: "center",
color: "white",
enable: false
},
{
bold: "true",
background: "#9c27b0",
color: "white",
textAlign: "center",
enable: false
},
{
bold: "true",
background: "#9c27b0",
textAlign: "center",
color: "white"
}, {
bold: "true",
background: "#9c27b0",
textAlign: "center",
color: "white"
}
]
}],
columns: [
{ width: 145 },
{ width: 145 },
{ width: 145 },
{ width: 300 },
{ width: 300 },
{ width: 300 },
{ width: 300 }
]
}]
});
function onSubmit(e) {
var arrofId = new Array();
var models = {};
var obj = "";
for (i = 0; i < JSON.stringify(e.data.created.length); i++) {
obj = e.data.created[i];
arrofId.push(obj);
}
arrofId.push(obj);
$.ajax({
type: "POST",
url: "/Agent/GetDataSpreadSheetSubmit1",
data: '{models: ' + JSON.stringify(arrofId) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('Record Saved Succesfully');
$('#grid').data('kendoGrid').dataSource.read();
$('#grid').data('kendoGrid').refresh();
},
error: function (xhr, httpStatusMessage, customErrorMessage) {
alert(xhr.responseText);
}
});
}
function onRead(options) {
$.ajax({
url: "../Agent/GetDataSpreadSheet",
type: "get",
dataType: "json",
success: function (result) {
debugger
options.success(result.data);
$("#spreadsheet").data("kendoSpreadsheet").refresh();
},
error: function (result) {
options.error(result);
}
});
}
$("#save").click(function () {
debugger
if (!$(this).hasClass("k-state-disabled")) {
dataSource.sync();
}
});
$("#cancel").click(function () {
if (!$(this).hasClass("k-state-disabled")) {
dataSource.cancelChanges();
}
});
});
}
any my controller action method for getting the list is below
[HttpGet]
public ActionResult GetDataSpreadSheet()
{
int statusID = 50;
var list = agentLogic.GetListByStatusID_forSpreadSheet(statusID).OrderBy(p => p.OrderID).ThenBy(o => o.OrderID);
HttpContext.Session["CheckSpreadsheetCount"] = list.Count();
return Json(new { total = list.Count(), data = list }, JsonRequestBehavior.AllowGet);
}
kendo spread sheet is not loading first time but after reload the browser its works as expected. Please help me what should i do? Please help me i am still unable to find any solution when it loads first time in any browser it creates problem after refresh it's working as expected.

Pagination using kendo grid does not work on page load

In my js. i am loading data using kendoGridOptions. I have mapped the data source which fetches all the records. I have configured pageable = true. However noticed that when page load the pagination option are not available they become available only on when i sort one of the columns. following is the configuration of my grid and data source
var enhancedGridOptions = mydataKendoGridManager.kendoGridOptions({
dataSource: myGridDataSource,
sortable: true,
scrollable: true,
editable:false,
resizable: true,
reorderable: true,
pageable: true,
columnResize: function (e) {
adjustLastColumn(e, this);
},
columns:
[
{
field: "dealType",
title: $.i18n.prop('buyType.label'),
width: "108px"
},
{
field: "myStatus",
title: $.i18n.prop('myStatus.label'),
width: "105px"
},
{
field: "action",
title: $.i18n.prop('action.label'),
width: "105px"
},
],
pdf:
{
fileName: "my_List_" + (new Date()).toString(myformat + "_HH:mm") + ".pdf",
allPages: true,
},
excel:
{
fileName: "my_List_" + (new Date()).toString(myformat + "_HH:mm") + ".xlsx",
allPages: true,
}
}
and my data source is configured as below
transport: {
read: function (e) {
myapi.rootGet("data/mylist?dealId=" + id, function (response) {
var data;
// console.log(response.data)
if (_.isString(response.data)) {
response.data = JSON.parse(response.data);
data = response.data;
setTimeout(function () {
e.success(data);
}, 10000);
}
else {
e.error("XHR response", response.status, JSON.parse(response.data));
}
});
},
},
schema:
{
model: {
id: "id",
fields: {
dealType: {
type: "string"
},
myStatus: {
type: "string"
},
action: {
type: "string"
},
}
},
parse:function(data)
{
return parseData(data);
}
},
serverSorting: false,
serverFiltering: false,
serverPaging: false
};
appreciate if someone can guide what is missing on pagination that does not work on page load.
Thanks,
Anjana
If you are getting "NaN - NaN of 500 items" like error at left bottom corner in grid, then you should add pageSize in dataSource Property.
var enhancedGridOptions = mydataKendoGridManager.kendoGridOptions({
dataSource: {
data: myGridDataSource,
pageSize: 50
},
....
....
....
pageable: {
pageSizes: [20, 30, 50, 100],
buttonCount: 5
}
});

Kendo Grid - how to remember selected row?

http://dojo.telerik.com/eWakO
Kendo Grid - here how should i modify above code to remember selected row? Example, if i have highlighted 4th row on 1st page and then scrolls to pages and come back to 1st page, then 4th row should be highlighted.
Thanks
Datha
Here is an example from the documentation:
http://docs.telerik.com/kendo-ui/controls/data-management/grid/how-to/Selection/persist-row-selection-while-paging
It relies on the change and dataBound events to save and restore selected rows by their IDs.
<div id="grid"></div>
<script>
$(function () {
var selectedOrders = [];
var idField = "OrderID";
$("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "http://demos.kendoui.com/service/Northwind.svc/Orders"
},
schema: {
model: {
id: "OrderID",
fields: {
OrderID: { type: "number" },
Freight: { type: "number" },
ShipName: { type: "string" },
OrderDate: { type: "date" },
ShipCity: { type: "string" }
}
}
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
height: 400,
selectable: "multiple",
pageable: {
buttonCount: 5
},
sortable: true,
filterable: true,
navigatable: true,
columns: [
{
field: "ShipCountry",
title: "Ship Country",
width: 300
},
{
field: "Freight",
width: 300
},
{
field: "OrderDate",
title: "Order Date",
format: "{0:dd/MM/yyyy}"
}
],
change: function (e, args) {
var grid = e.sender;
var items = grid.items();
items.each(function (idx, row) {
var idValue = grid.dataItem(row).get(idField);
if (row.className.indexOf("k-state-selected") >= 0) {
selectedOrders[idValue] = true;
} else if (selectedOrders[idValue]) {
delete selectedOrders[idValue];
}
});
},
dataBound: function (e) {
var grid = e.sender;
var items = grid.items();
var itemsToSelect = [];
items.each(function (idx, row) {
var dataItem = grid.dataItem(row);
if (selectedOrders[dataItem[idField]]) {
itemsToSelect.push(row);
}
});
e.sender.select(itemsToSelect);
}
});
});
</script>

jqplot json_encode data not rendering line graph

I return these 2 string from controller in codeigniter using json_encode for jqplot line grapgh
here i fetch the data
$(document).ready(function(){
$(".stats").click(function(){
var site_id = $(this).attr("id");
$.ajax({
url: site_url+"statistics/fetch_stats_data/"+site_id,
async: false,
type: "POST",
data: "type=article",
dataType: "json",
success: function(data) {
stat_events_plot_graph(data['activity_events'], data['activity_tricks']);
}
})
});
});
plot data structure returned as php string from above ajax
[["10/21/2014 05:50",1]]
plot ticks structure returned as php string from above ajax
[[1,"Today"]]
when i send this data to the plot the graph is not rendered
function stat_events_plot_graph(activity_events_live, activity_tricks_live) {
var plot2 = $.jqplot('events', [activity_events_live], {
title: 'Events',
seriesDefaults: {
rendererOptions: {
smooth: false,
animation: {
show: true
}
}
},
legend: { show: false },
axes: {
xaxis: {
renderer: $.jqplot.DateAxisRenderer,
tickOptions: { formatString: '%b %#d, %#I %p',angle: -90 }
},
yaxis: {
ticks : activity_tricks_live,
}
},
series: [{ lineWidth: 4,
markerOptions: { style: 'square' }
}],
series: [
{ label: 'Toronto' },
{ label: 'New York' }
],
});
}
how do I convert those 2 strings to work with the line graph ?

jqGrid Form Editing - How to POST Edit row to the sql server

I am using jqGrid in my sharepoint webpart and trying to use Form Editing grid.
I dont know how to post data back to the sql server database for add/update/delete.
I am using WCF service that will accept JSON data from the grid.
WCF Method:
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped,
Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
bool UpdateProjectDeliverable(string ProjectName, string CriticalItemInfo);
JQGrid - Form Edit:
$('#PrjDeliverablesGrid').jqGrid({
datatype: 'json',
colNames: ['ActivityDescription', 'Type', 'CompletionDate'],
colModel: [
{ name: 'ActivityDescription', index: 'ActivityDescription', width: 200, sortable: false, editable: true, edittype: "textarea", editoptions: { rows: "2", cols: "10" }, formoptions: { rowpos: 1, elmprefix: "(*)" }, editrules: { required: true} },
{ name: 'Type', index: 'Type', width: 90, editable: true, edittype: 'select', editoptions: {
value: function () {
var EditVal = LoadDeliverableTypes();
return EditVal;
}
}, /*editoptions: { value: "H:HandOver; CD:Charter (Draft); CF:Charter (Final); P0:Proto 0; P1:Proto 1; P2:Proto 2; P3:Proto 3" },*/formoptions: { rowpos: 2, elmprefix: " " }
},
{ name: 'CompletionDate', index: 'CompletionDate', width: 90, editable: true, sorttype: 'date', formatter: 'date',
editoptions: { size: 12,
dataInit: function (element) {
$(element).datepicker({ dateFormat: 'mm/dd/yyyy' });
},
defaultValue: function () {
var currentTime = new Date();
var month = parseInt(currentTime.getMonth() + 1);
month = month <= 9 ? "0" + month : month;
var day = currentTime.getDate();
day = day <= 9 ? "0" + day : day;
var year = currentTime.getFullYear();
return month + "/" + day + "/" + year;
}
},
formoptions: { rowpos: 3, elmprefix: "(*)", elmsuffix: "mm/dd/yyyy" }, editrules: { required: true }
}
],
rowNum: 10,
pager: '#pagerPrjDeliverables',
sortname: 'id',
sortorder: 'desc',
viewrecords: true,
autowidth: true,
gridview: true,
caption: 'Critical Activities/Deliverables'
});
$('#PrjDeliverablesGrid').jqGrid('navGrid', '#pagerPrjDeliverables',
{ view: true, edit: true, add: true, del: true },
{ edit: true,
afterShowForm: function (eparams) {
$('#PrjDeliverablesGrid').jqGrid('setGridParam', { SelCriticalItem: function () {
var row_id = $('#PrjDeliverablesGrid').jqGrid('getGridParam', 'selrow');
var tempCriticalInfo = new object();
tempCriticalInfo.DeliverableName = $('#PrjDeliverablesGrid').jqGrid('getCell', row_id, 'ActivityDescription');
var DeliverableTypeName = $('#PrjDeliverablesGrid').jqGrid('getCell', row_id, 'Type');
tempCriticalInfo.DeliverableTypeID = GetDeliverableTypeIDFromName(DeliverableTypeName);
tempCriticalInfo.CompletionDate = $('#PrjDeliverablesGrid').jqGrid('getCell', row_id, 'CompletionDate');
return tempCriticalInfo;
}
});
},
// serializeEditData: function (projDeliverableAddEditParams) { //USED ON EDIT
// return JSON.stringify(projDeliverableAddEditParams);
// },
onclickSubmit: function (params, SelCriticalItem) {
var Url = "http://vm0301cch:19511/_layouts/AGCO.PB.SharePointUI/WCFPBUtility/WCFPBUtility.svc";
var SelProjectName = document.getElementById("txtProjectID").value;
var data;
SelDelvProjectName = SelProjectName;
$('#PrjDeliverablesGrid').jqGrid({
params.url = Url + "/UpdateProjectDeliverable",
datatype: 'json',
mtype: 'POST',
editData: { ProjectName: SelDelvProjectName },
ajaxEditOptions: { contentType: 'application/json',
success: function (data) {
alert('Deliverables loaded successfully');
},
error: function (data) {
alert('Deliverables loading failed');
}
}
});
},
jqModal: true,
checkOnUpdate: true,
savekey: [true, 13],
navkeys: [true, 38, 40],
checkOnSubmit: true,
reloadAfterSubmit: false,
recreateForm: true,
closeOnEscape: true,
bottominfo: "Fields marked with (*) are required"
}); // edit options
Please help.