I am trying to bind Data from database to KendoUI Grid but Data is not Showed up... I am getting data from database successfully converting into serialized code but data does not showed up in Kendo Grid.. plz help me...
<div id="example" class="k-content">
<div id="grid"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#grid").kendoGrid({
dataSource:
{
type:"odata",
serverPaging: true,
serverSorting:true,
pageSize:100,
transport:
{
read:
{
url:"Fetchdata.aspx",
contentType: "application/json;charset=utf-8",
dataType: "odata",
jsonReader:
{
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false
}
}
}
},
height:100,
scrollable:
{
virtual: true
},
sortable: true,
columns: [
"dptId",
{ title: "Name", field: "dptName" },
{ title: "Description", field: "dptdescription" }
]
});
});
</script>
</div>
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(GetData());
Response.End();
}
protected string GetData()
{
EmployeeBM empbm = new EmployeeBM();
List < Departement> list= new List<Departement>();
list = empbm.BindDepartment();
return GridData(1, 1,list.Count, list);
}
public string GridData(int noOfPages, int startPage, int noOfRecords, List<Departement> list)
{
var gridData = new
{
total = noOfPages,
page = startPage,
records = noOfRecords,
rows = list,
};
var jsonSerializer = new JavaScriptSerializer();
return jsonSerializer.Serialize(gridData);
}
I see quite a few issues in your code:
The dataType cannot be set to "odata". Try "json". To quote the jQuery documentation:
Default: Intelligent Guess (xml, json, script, or html)
The Kendo DataSource type is also set to "odata" but your page is clearly not an OData service. Remove that.
You are setting jsonReader which is not supported by the Kendo DataSource. I guess you need to use the schema setting.
Related
I am converting Kendo dropdownlist from the existing code into Kendo multiselect.
Role Code: Currently Dropdownlist (converting to Kendo multiselect).
I am not getting the correct output.
I have the following code:
<div class="col-md-4 form-group">
#Html.LabelFor(model => model.RoleCode, htmlAttributes: new { }) <span style="color: Red">*</span>
<select id="DDRolecode" multiple="multiple" data-placeholder="Select attendees...">
</select>
</div>
...
...
var url = '#Url.Action("GetRoleCode", "FlowGenerator")';
url = url + '?FlowID=' + flowid + '&RegID=' + RegId;
$.ajax({
url: url,
dataType: 'json',
type: 'POST',
success: function (result) {
debugger;
//$("#DDRolecode").kendoDropDownList({
// dataTextField: "Name",
// dataValueField: "ID",
// optionLabel: "Select",
// dataSource: result
//});
$("#DDRolecode").kendoMultiSelect({
dataTextField: "Name",
dataValueField: "ID",
dataSource: result,
});
var selectedData = [];
for (var i = 0; i < result.length; i++) {
selectedData.push({
text: result[i].Name,
value: result[i].ID
})
}
DDRoleCode.dataSource.data(selectedData);
//DDRoleCode.setDataSource(selectedData);
DDRoleCode.value('');
DDRoleCode.enable(true);
},
error: function (data) {
debugger;
var itemRow = "<ul id='listError'><li>" + "Data Not Bind" + "</li></ul>";
FUNMessageBox(itemRow, "E", 0, 0, "", "");
// alert("error");
}
});
The below is the controller code where I am getting the role codes:
public JsonResult GetRoleCode(int FlowID,int RegID)
{
IEnumerable<GenericValues1> RoleCode = _repository.Context.Database.SqlQuery<GenericValues1>("PROC_GET_ROLECODE #DATA_FLOW_ID={0},#REG_ID={1}", FlowID, RegID).ToList().AsQueryable();
// ViewBag.Tariffs = RoleCode;
return Json(RoleCode, JsonRequestBehavior.AllowGet);
}
As you can see, I tried using the multiselect functionality in the above code. But it didn't work.
To avoid the long comment chain.
From the second image you have provided it looks like the issue of multiple multiselects being added to the same item. This is due to you attaching a a new multiselect control to the same input.
this is a simple fix really.
There are two ways to fix it.
1) Destroy the kendo widget and recreate it
2) Assuming the same structure is used in the underlying datasource and other settings just apply the new datasource data to the widget.
Here is a dojo showing you both examples:
https://dojo.telerik.com/UxetijUy/2
Personally I would go with option 2 as it is a cleaner solution and avoids having to constantly destroy and recreate widgets.
So if you change the required person in the second example it will take a random number of people from the data array for the multiselect and then rebind those options to that control.
So that is all you would have to do with your ajax call is once you have the result just apply the new data to the datasource and then you don't need to keep recreating the widget as you are currently doing.
So in your example:
$("#DDRolecode").data('kendoMultiSelect').value(null);
$("#DDRolecode").data('kendoMultiSelect').dataSource.data(selectedData);
This ensures you have cleared off any selected items before you have attached the new data source.
If you need more info on what is happening. Please ask and I will update my answer accordingly.
The below code worked for me:
$(document).ready(function () {
debugger;
$("#DDRolecode").kendoMultiSelect({
dataTextField: "Name",
dataValueField: "ID",
});
....
....
//go to controller and call Sp and get the result
success: function (result) {
debugger;
var multiSelect = $('#DDRolecode').data("kendoMultiSelect");
multiSelect.value([]);
$("#DDRolecode").data("kendoMultiSelect").setDataSource(new kendo.data.DataSource({ data: result }));
var selectedData = [];
for (var i = 0; i < result.length; i++) {
selectedData.push({
Text: result[i].Name,
Value: result[i].ID
})
}
I have a static pie-chart created using chartJS and now I want to provide the data and labels from an asp.net webservice(asmx) to show the actual data that comes from the database but I don't know how to do that.
This is the Static Chart Code
<!doctype html>
<html>
<head>
<title>Pie Chart</title>
<script src="../../dist/Chart.min.js"></script>
<script src="../utils.js"></script>
</head>
<body>
<div id="canvas-holder" style="width:40%">
<canvas id="chart-area"></canvas>
</div>
<script>
var config = {
type: 'pie',
data: {
datasets: [{
data: [420,576,812],
backgroundColor: [
"#3e95cd", "#8e5ea2", "#3cba9f"
],
label: 'Labels'
}],
labels: [
'iPhone',
'Windows Phone',
'Samsung'
]
},
options: {
responsive: true
}
};
window.onload = function () {
var ctx = document.getElementById('chart-area').getContext('2d');
window.myPie = new Chart(ctx, config);
};
</script>
</body>
</html>
The Data I want to Show
Phone as Chart Label and Amount as Chart-Data
-------------------------
-Phone - Amount-
-------------------------
-iPhone - 323 -
-Windows-Phone - 210 -
-Samsung - 860 -
-------------------------
The Web Service that fetch the data
[WebMethod]
public void GetTotalPhoneSales()
{
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
List<TotalSales> totalSales = new List<TotalSales>();
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetTotalPhoneSales", con)
{
CommandType = CommandType.StoredProcedure
};
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
TotalSales PhoneSale = new TotalSales
{
Amount = Convert.ToInt32(rdr["Amount"]),
Phone = rdr["Phone"].ToString()
};
totalSales.Add(PhoneSale);
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(totalSales));
}
Expected output
You may call the web service method from Jquery Ajax function and return the values.
What you have to change is
1) Change the return type of your web method to string[][](Array of string Arrays:because we need to return two arrays)
2) Call this web method with the help of Jquery ajax function and in the success function assign the data and label options with respective arrays received from the jquery ajax call.
documentation of Jquery ajax function
Finally I solved it like this
<script>
//make an ajax call to the webservice
//then use `chartlabel` as label and `chartData` as Data
var chartLabel= [];
var chartData= [];
$.ajax({
url: 'TestService.asmx/GetTotalPhoneSales',
method: 'post',
dataType: 'json',
success: function (data) {
$(data).each(function (index, item) {
chartLabel.push(item.Phone);
chartData.push(item.Amount);
});
},
error: function (err) {
alert(err);
}
});
var config = {
type: 'pie',
data: {
datasets: [{
data: chartData,
backgroundColor: [
"#3e95cd", "#8e5ea2", "#3cba9f"
],
label: 'Labels'
}],
labels: chartLabel
},
options: {
responsive: true
}
};
window.onload = function () {
var ctx = document.getElementById('chart-area').getContext('2d');
window.myPie = new Chart(ctx, config);
};
</script>
Note: Its better to assign the backgroundColor programmatically, so that when new items are added to the database then those items will not show up with same color on the chart by default.
thanks for the hint #Gagan Deep
I'm developing a web site in MVC 5 and I'm using google chart to display some chart for my data. I'm using the line chart for a data which have a value and a date. Something like the follow:
class ChartData
{
public double Value { get; set; }
public DateTime Date { get; set; }
};
In my controller I have a request handler to generate the data for the chart:
public JsonResult GenerateChartData(int id)
{
List<ChartData> list = new List<ChartData>();
// some code to populate the list
return Json(list, JsonRequestBehavior.AllowGet);
}
Everything works fine except that the X axis which should show the date time sequence is formatted in the wrong way. The looks like absolute time not in readable date format.
see the chart output
thanks for any answer
google charts will accept dates in a couple ways,
which depend on how the data table, used to draw the chart, is loaded...
1)
if you're using one of the following methods to load the data table...
addRow(), addRows(), arrayToDataTable()
the date will need to be a javascript date object,
created using the new keyword,
any valid constructor will work
new Date();
new Date(value);
new Date(dateString);
new Date(year, month[, date[, hours[, minutes[, seconds[, milliseconds]]]]]);
2)
if using json to load the data table directly...
var data = new google.visualization.DataTable(jsonData);
the following string format can be used...
which needs to be a string value (wrapped in quotes), without the new keyword...
"Date(Year, Month, Day, Hours, Minutes, Seconds, Milliseconds)"
where Month is zero-based
"Date(2017, 4, 16)" // <-- 5/16/2017
This is the way to load the data inside a java script. But in my case the data are generate in json format by a request to the controller. I post the code of my page
#model BDF.RemoteData.Data.TagData
#{
ViewBag.Title = "Chart";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>[[[Grafico]]]</h2>
<input type="hidden" id="idInput" data-value="#ViewBag.id" />
<input type="hidden" id="idSystem" data-value="#ViewBag.system" />
<input type="hidden" id="idStart" data-value="#ViewBag.start" />
<input type="hidden" id="idEnd" data-value="#ViewBag.end" />
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1",
{
packages: ["corechart"]
});
google.setOnLoadCallback(drawChart);
function drawChart()
{
var id = $("#idInput").data("value");
var system = $("#idSystem").data("value");
var start = $("#idStart").data("value");
var end = $("#idEnd").data("value");
$.ajax(
{
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: '#Url.Action("GenerateChartData")',
data:
{
id: id,
system: system,
start: start,
end: end
},
type: "GET",
error: function (xhr, status, error)
{
var err = eval("(" + xhr.responseText + ")");
toastr.error(err.message);
},
beforeSend: function ()
{
},
success: function (data)
{
HistDashboardChart(data);
return false;
},
error: function (xhr, status, error)
{
var err = eval("(" + xhr.responseText + ")");
toastr.error(err.message);
},
complete: function ()
{
}
});
return false;
}
//This function is used to bind the user data to chart
function HistDashboardChart(data)
{
$("#Data_Chart").show();
var dataArray = [
['Date', 'Value']
];
$.each(data, function (i, item)
{
dataArray.push([item.Date, item.Value]);
});
var data = google.visualization.arrayToDataTable(dataArray);
var options = {
legend:
{
position: 'bottom',
textStyle:
{
color: '#f5f5f5'
}
},
colors: ['#34A853', 'ff6600', '#FBBC05'],
backgroundColor: '#454545',
hAxis:
{
title: 'Time',
titleTextStyle:
{
italic: false,
color: '#00BBF1',
fontSize: '20'
},
textStyle:
{
color: '#f5f5f5'
}
},
vAxis:
{
baselineColor: '#f5f5f5',
title: 'Values',
titleTextStyle:
{
color: '#00BBF1',
italic: false,
fontSize: '20'
},
textStyle:
{
color: '#f5f5f5'
},
viewWindow:
{
min: 0,
format: 'long'
}
},
curveType: 'function',
};
var chart = new google.visualization.LineChart(document.getElementById('Data_Chart'));
chart.draw(data, options);
return false;
};
</script>
<div id="Data_Chart" style="width: 100%; height: 500px"> </div>
As you can see the job id done by the request url: '#Url.Action("GenerateChartData")'
Then the returned data are pushed into an array the the code
var dataArray = [
['Date', 'Value']
];
$.each(data, function (i, item)
{
dataArray.push([item.Date, item.Value]);
});
In this case I'm assuming that item.Date is already in a datetime format but maybe I have to format it in a special way.
The output of the console.log(item.Date) is the following:
/Date(1494937128000)/
/Date(1494937133000)/
/Date(1494937138000)/
/Date(1494937143000)/
/Date(1494937148000)/
/Date(1494937153000)/
/Date(1494937158000)/
/Date(1494937163000)/
Which looks strange I think, doesn't it?
Ok I got it. Reading this article made everything clear
How to parse JSON to receive a Date object in JavaScript?
I modified the java script code inside my page in the following way:
var dataArray = [
['Date', 'Value']
];
$.each(jsondata, function (i, item) {
var d = new Date(parseInt(item.Instant.substr(6)));
dataArray.push([d, item.Value]);
});
Now it works perfectly
I have an MVC Edit View that contains Contact Information that is of course editable. In that view I want to add a section containing a JQGrid allowing the user to CRUD notes for the Contact but my grid is not loading with data nor is the method on the controller being called. Can anyone give me any insite?
View Code
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-info">
Contact Note</h3>
</div>
<div class="panel-body">
<div class="scrollableContainer" style="margin-top: -10px;">
<table id="JQGrid1"></table>
<div id="JQGrid1_pager"></div>
</div>
</div>
</div>
<script>
$("#JQGrid1").jqGrid({
url: '#Url.Action("GetNotes", "Contact")',
mtype: "GET",
datatype: "json",
page: 1,
jsonReader: { id: document.getElementById('SelectedContact_ContactID').value },
prmNames: { id: document.getElementById('SelectedContact_ContactID').value },
colNames: ["Id", "ContactId", "Note", "Date Created", "Created By"],
colModel: [
{ key: true, width: 50, name: "ID", hidden: false },
{ width: 60, name: "ContactID", hidden: false },
{ width: 460, name: "Note", hidden: false },
{ width: 160, name: "DateCreated",
formatter: "date", formatoptions: { srcformat: "m/d/Y h:i:s A", newformat: "mm-dd-yyyy" }, hidden: false },
{ width: 160, name: "CreatedBy", hidden: false },
],
height: "auto",
caption: "Notes",
rowNum: 5,
pager: "#JQGrid1_pager",
});
</script>
Controller Code
[HttpGet]
public JsonResult GetNotes(int id)
{
var gridModel = new ContactNotesJQGridModel();
var resultset = _contactNoteRepository.GetNotes(id);
return gridModel.ContactNotesGrid.DataBind(resultset.AsQueryable());
}
GridModel Class
public class ContactNotesJQGridModel
{
public JQGrid ContactNotesGrid { get; set; }
public ContactNotesJQGridModel()
{
ContactNotesGrid = new JQGrid
{
Columns = new List<JQGridColumn>()
{
new JQGridColumn {DataField = "ID", PrimaryKey = true},
new JQGridColumn {DataField = "ContactId"},
new JQGridColumn {DataField = "Note"},
new JQGridColumn {DataField = "DateCreated"},
new JQGridColumn {DataField = "CreatedBy"},
}
};
}
Then in the Edit Call for the Contact in the Contact Controller I set model.ContactNotesGrid = new ContactNotesJQGridModel GetNotes(int id) is never executed eventhough it's specified in the jquery.
You should use postData to add custom parameter to the server response:
postData: { id: 11 }
or
postData: {
id: function () {
return document.getElementById('SelectedContact_ContactID').value;
}
}
You need additionally modify the code of the server to use something like
return Json(someObjectWithReturnedData, JsonRequestBehavior.AllowGet);
I recommend you to add loadError callback to the list of jqGrid option (see the answer) and add gridview: true and autoencode: true option to jqGrid.
P.S. About the errors like "unable to get value of the property integer", "unable to get value of the property decimalSeperator". You should verify that you included locale file like i18n/grid.locale-en.js before jquery.jqGrid.min.js (see the documentation).
Try this :
Check 1:
Move your Jquery script inside the document ready event:
$( document ).ready(function() {
console.log( "ready!" );
});
Check 2:
Check weather your server request having any problem or not:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Response.Clear();
}
Add the above code in your Global.asax and make sure there is no exception during the call. (Put Break point and check)
Check 3:
Watch your browser console log (F12). If there is any exception log please provide that.
Check 4:
Make sure if the call is success the expected json format is valid or not. In most of the cases it will be the major cause.
The above's are just my guesses / this is what i do first, if i have a prob. :)
Here's my tree view:
function CreateNotificationTree(UserId)
{
var data = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: "../api/notifications/byuserid/" + UserId,
contentType: "application/json"
}
},
schema: {
model: {
children: "notifications"
}
}
});
$("#treeview").kendoTreeView({
dataSource: data,
loadOnDemand: true,
dataUrlField: "LinksTo",
checkboxes: {
checkChildren: true
},
dataTextField: ["notificationType", "NotificationDesc"]
});
}
I added the config "dataUrlField" but I'm unsure on how to configure the dataTextField "NotificationDesc" to be a hyperlink that is found IN THE API as well.
The API "../api/notifications/byuserid/" brings back the data for the tree view along with the link I need. Here's what the API returns:
<ArrayOfNode xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http....WebUI.Controllers" debug="true">
<script id="FirebugLite" firebugIgnore="true" extension="Chrome"/>
<Node>
<notificationType>Edit Items</notificationType>
<notifications>
<Notification>
<ActionPageName>abc/ViewMembers.aspx</ActionPageName>
<ID>10285433</ID>
<NotificationDesc>2013 project</NotificationDesc>
<NotificationLink>
//the link I need is here
</NotificationLink>
<Params>...</Params>
</Notification>
...
I figured out how to do it:
$("#treeview").kendoTreeView({
dataSource: data,
loadOnDemand: true,
dataUrlField: "LinksTo",
checkboxes: {
checkChildren: true
},
dataTextField: ["notificationType", "NotificationDesc"],
select: treeviewSelect
});
function treeviewSelect(e)
{
var node = this.dataItem(e.node);
window.open(node.NotificationLink, "_self");
}