KendoUI Remote datasource : assign url parameter a value from javascript variable - kendo-ui

I'm using KendoUI to create charts from a remote datasource which is JSON file.
When I assign the url parameter(inside datasource object) a remote path ,pointing to the JSON the chart doesn't appear .
Say Like,
var myVar="some remote url";
dataSource: {
transport: {
read: {
url: myVar,
dataType: "json"
}
}
}
On the other hand if I directly specify the url as:
url: "http://myserver-name/somefile.json"
I can see the chart being displayed.
I cannot figure out what I'm doing wrong.

It should work! Check the following running on jsfiddle.
var url = "http://demos.kendoui.com/service/Products";
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: url,
dataType: "jsonp"
}
},
pageSize: 4,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: {
editable: false,
nullable: true
},
ProductName: "ProductName"
}
}
}
});
$("#kendogrid").kendoGrid({
dataSource: dataSource,
columns: [
{
field: "ProductID",
title: "ID"},
{
field: "ProductName",
title: "Name"}
]
});​
And this is the HTML:
<div id="kendogrid"></div>​
It defines an external URL and sets it to a variable ( url) and then uses the resulting DataSource.
Check for differences or post a code as complete as possible in jsfiddle or jsbin.

well , your solution worked for me but in different way.I was getting the url value from a .cs file and storing inside an javascript variable.
var URL="<%=myCSvariable%>";
But this alone doesnt works...:(
I had to modifiy the URL variable value as,
var completeURL="\"" + URL + "\"";
and then create dataSource object as,
var mydataSource = new kendo.data.DataSource({
transport: {
read: {
url: URL, // this is the tricky part. Using 'completeURL' here doesnt creates my chart , instead 'URL' works just fine.
dataType: "json"
}
}
});
I know its STRANGE but that's how it worked for me..
Anyways, Thanks a ton..:)

Related

Kendo DropDownList Not Binding Data

I am using a Kendo dropdownlist to display data made from a remote service call.
First, here is the definition in the HTML template:
<select
kendo-drop-down-list
k-options="dropdownOptions"
k-ng-delay="dropdownOptions">
</select>
Next, here is the code to populate the dropdown from an AngularJS controller:
var myUrl = '(url of REST service)';
$scope.dropdownOptions = {
dataSource: {
transport: {
read: {
url: myUrl,
dataType: 'json',
type: 'POST',
contentType: "application/json;charset=ISO-8859-1"
},
parameterMap: function (data, type) {
const req = {
"PARAMS": $scope.params
};
return JSON.stringify(req);
}
}
},
dataTextField: 'DESCRIPTION',
dataValueField: 'VALUE',
schema: {
type: "json",
data: "resultData",
model: {
id: "VALUE",
fields: {
"VALUE":{field: "VALUE", type: "string"},
"DESCRIPTION":{field: "DESCRIPTION", type: "string"}
}
}
}
};
(Note: the REST service requires data to be provided as a JSON object via POST, hence the type and parameterMap).
I have confirmed that the data to populate the dropdown is being returned from the REST service as an array under the key "resultData":
{
"resultData":[{"DESCRIPTION":"Whatever","VALUE":"VALUE1"},...]
}
Can anyone help me?
Update
I am also seeing "e.slice is not a function" in my dev console.
Edit
Added id field to model, no effect.
The problem was that schema should have been a child of dataSource. Once I fixed that, the data began to display.

Kendo UI does not call create if a function is specified

Using Kendo.web.js versions 2013.2.716 and 2012.3.1315, I am trying to use a function in my transport.create rather than calling a URL. What I find is that the function does not get called. Instead a default URL is called and the resulting HTML appears to cause an error in the bowels of kendo because it is expected to be JSON instead.
I assume that this is some type of configuration error, but I can't figure out where the problem is.
Here is a snippet of the code:
var clientListDS = new kendo.data.DataSource({
transport: {
read: {
url: window.baseUrl + 'HealthCheck/ClientSummary',
dataType: 'json',
type: 'POST'
},
create: function(a,b,c) { alert('Create'); },
createY: window.baseUrl + 'HealthCheck/DontCallMe',
createX: {
url: window.baseUrl + 'HealthCheck/DontCallMe',
dataType: 'json',
type: 'POST'
},
whatWeWantCreateToDo: function () {
showChooseDialog('Some Random String', 'Select Client', OnRefreshInactiveClientList);
},
destroy: function () {
alert('destroy');
},
update: function () {
alert('update');
}
},
autoSync: true,
schema: {
model: {
id: 'ID',
fields: {
ID: { required: false, type: 'number', nullable: true },
ClientName: { type: 'string' },
ClientTag: { type: 'string' },
Status: { type: 'string' }
}
}
}
});
Then I use the resulting data source to build a grid like this:
$('#cClientGrid').kendoGrid({
dataSource: clientListDS,
columns: [
{ field: 'ClientTag', title: 'Tag'},
{ field: 'ClientName', title: 'Name' },
{ field: 'Status' }
],
editable: {
mode: 'incell',
createAt: 'bottom'
},
edit: function (pEvent) {
if (pEvent.model.isNew())
alert('create');
else
alert('Edit');
},
toolbar: ['create']
});
Some behavior that is worthy of note:
You see several attempts at the create configuration. If I use CreateY or CreateX, it will call the resulting URL. If I use Create or WhatWeWantCreateToDo, I end up downloading the containing page with each element of my schema as get string items (I assume this is some type of default behavior as I can't find a reference to the URL which is downloaded).
When I turn off autoSync, the grid will call its edit function when I use the toolbar to create a new item. When I turn on autoSync, the edit function does not get called. Instead the data source create functionality runs.
Any thoughts or insight on how I might be able to call a function instead of a URL will be appreciated.
First make in transport everything being an URL or a function, do not mix them up.
If you need to implement read as a function, you simply do:
transport: {
read : function (options) {
$.ajax({
url: window.baseUrl + 'HealthCheck/ClientSummary',
dataType: 'json',
type: 'POST',
success : function (result) {
options.success(result);
}
});
},

Kendoui DataSource odata $expand not working

I have a mobile listview bound to kendoui datasource pointing to an odata service. I have a $expand hint in the datasource config to expand "Patient" property of "Claim" object, but looking the url of the odata query, the kendoui datasource is not generating the $expand code in the querystring. How can I get the kendoui datasource to generate correct $expand instruction on the querystring?
OData query string genereated: http://localhost:1839/OData.svc/Claim?$callback=jQuery20207924230222124606_1374374358450&%24inlinecount=allpages&%24format=json&%24top=10
<script>
$(function () {
var app = new kendo.mobile.Application(document.body, {
transition: 'slide'
});
OData.defaultHttpClient.enableJsonpCallback = true;
var data = new kendo.data.DataSource({
type: "odata", // specifies data protocol
pageSize: 10, // limits result set
transport: {
read: "http://localhost:1839/OData.svc/Claim",
dataType: "json",
data: {
$expand: "Patient"
}
},
schema: {
model: {id: "Id"},
data: function (data) {
return data.d.results;
},
total: function (data) {
return data.d.__count;
}
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true
});
$("#lst").kendoMobileListView(
{
template: "<strong>${data.ClaimNumber}</strong><br/>",
filterable: {
field: "ClaimNumber",
operator: "contains"
},
dataSource: data
});
});
</script>
The data and $expand belong inside the read object. You were getting close in your answer.
var dataSource = new kendo.data.HierarchicalDataSource({
type: "odata",
transport: {
read: {
// See http://www.odata.org/documentation/odata-v2-documentation/uri-conventions/ for OData URI conventions
// OData: ~/api/Users?$inlinecount=allpages&top=2
// OData: ~/api/Users?$inlinecount=allpages - includes odata.count
// OData: inline filtering: ~/api/Users?$filter=USERNAME eq 'asgro'
// to include hierarchical data, use the OData /api/UserGroups?$expand=USER
// To reduce the payload sice, the query ~/api/UserGroups will only include the USERGROUP entities, and not any navigation property content
url: "/api/UserGroups",
data: {
$expand: "USERS"
},
dataType: "json" // the default result type is JSONP, but WebAPI does not support JSONP
},
I added this right in the transport/read/url, rather than a separate data:
var dataSource = new kendo.data.HierarchicalDataSource({
type: "odata",
transport: {
read: {
// See http://www.odata.org/documentation/odata-v2-documentation/uri-conventions/ for OData URI conventions
// OData: ~/api/Users?$inlinecount=allpages&top=2
// OData: ~/api/Users?$inlinecount=allpages - includes odata.count
// OData: inline filtering: ~/api/Users?$filter=USERNAME eq 'asgro'
// to include hierarchical data, use the OData /api/UserGroups?$expand=USER
// To reduce the payload sice, the query ~/api/UserGroups will only include the USERGROUP entities, and not any navigation property content
url: "/api/UserGroups?$expand=USERS",
dataType: "json" // the default result type is JSONP, but WebAPI does not support JSONP
},
.
.
.
read: {
url: "http://localhost:1839/OData.svc/Claim",
dataType: "json",
data: {
$expand: "Patient"
}
}
The data only read options.

kendo grid delete command not working

i have developed a web application using kendo ui tools and theres a kendo grid with batch edit mode..
but when i press the delete button for any record in kendo grid it will erase from the list in grid but actually not in the data source.when i reload the page or grid the deleted item will still exist..
here is the code of my grid
<div id="grid">
</div>
<script type="text/javascript">
$("#submitMarketUser").click(function () {
var grid = $("#grid").data("kendoGrid");
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "WholeSaleTrade/GetTradeProductDetail",
dataType: "json",
data: {
test: $("#Names").val()
}
},
destroy: {
url: "WholeSaleTrade/DeletePro",
type: "POST",
dataType: "jsonp",
data: {
DAKy: $("#Names").val(),
DIKy: $("#btntxt").val()
}
},
create: {
url: "WholeSaleTrade/CreateProduct",
type: "POST",
dataType: "jsonp",
data: {
AKy: $("#Names").val(),
IKy: $("#btntxt").val()
}
}
},
pageSize: 5,
schema: {
model: {
id: "ProductKey",
fields: {
ProductKey: { editable: false, nullable: true },
ProductName: { validation: { required: true} }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
editable: true,
toolbar: ["create", "save"],
autobind: true,
pageable: true,
columns: [
{ field: "ProductName", title: "Product Name",
editor: function (container, options) {
var model = options.model;
$('<input id="btntxt" name="' + options.field + '"/>').appendTo(container).kendoComboBox({
dataSource: {
type: "POST",
transport: {
read: {
url: "MarketInformation/PopulateProducts",
success: function (data) {
var prod = data[0];
model.set("ProductName", prod.ItmNm);
model.set("ItmKy", prod.ItmKy);
model.set("UserKey", $("#Names").val());
}
}
}
},
dataValueField: "ItmKy",
dataTextField: "ItmNm"
});
}
},
{ command: ["destroy"], title: " " }
]
});
});
</script>
can not identify that where is the fault going and can somebody please help me to solve this matter.
There are three common reasons delete won't work:
1. Not setting editable of grid to inline or popup. The deleted items will be automatically processed through transport destroy only for "inline"/"popup" edit modes. Ex:
editable: {
mode: "inline",
}
//or
editable: "inline"
2. If on your datasource, you have the batch flag set to true, this means the datasource will make the call only after you tell it to, e.g calling sync(). Ex:
var dataSource = new kendo.data.DataSource({
batch: true,
//.....
});
//... in some where e.g in a save button click event call the following line:
dataSource.sync();
3. You should define id to your primary key of database field name inside model of datasource. Ex:
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
}
}
So the problem with your code is first one, i.e you did not set editable to inline or popup
If you choose not to include editable.mode in order to utilize the in-cell editing, you can set the toolbar of the grid to include the option save:
$("#grid").kendoGrid({
dataSource: {
transport: {
....
},
schema: {
....
}
},
toolbar: ["create", "save", "cancel"],
columns: [
....
],
editable: true
});
This will create a save button at the toolbar of the grid. After deleting any records by clicking the destroy command button, click on the save button to have the grid to make an Ajax call to the server to delete the record.
If you would rather delete the record automatically without including the save button, you could add a change event handler to the datasource of the grid:
$("#grid").kendoGrid({
dataSource: {
transport: {
....
},
schema: {
....
},
change: function(e) {
if (e.action === "remove") {
this.sync();
}
}
},
columns: [
....
],
editable: true
});
This will automatically sync the changes you made to the grid with the server when there's a data change.
Hmm try not including type: "POST", and see if it now works since as far as I can see that bit isn't included on the demo's and I don't think I included it when I last did inline edits/deletes.
I had put an arbitray name for an int on the server Delete Method.
[HttpPost]
public ActionResult DeleteRandomTest(Int32 randomTestId)
{
...
}
The default modelbinder was probably looking for a property called Id (same as the primary key of my type according to the configuration of the model).
.Model(config => config.Id(p => p.Id))
In fact, I proved this by changing the signature to the following:
[HttpPost]
public ActionResult DeleteRandomTest(Int32 Id)
{
...
}
My break point was hit after that.
Ultimately, I used the full type as the parameter as shown in the Kendo examples because I didn't want to have poorly named parameter names (not camel case) in the action. Shown as follows:
[HttpPost]
public ActionResult DeleteRandomTest([DataSourceRequest]
DataSourceRequest request, RandomDrugTest randomDrugTest)
{
...
}
This seems to the be the reason it wasn't working.
I had the same issue. My issue was caused by having a data property in the kendo model. Example:
{id: 1, data: ""}

Kendo AutoComplete does not re-query the datasource when retyping search string

I have a problem with the Kendo AutoComplete widget.
I am trying it to query the datasource after the user has entered the first two characters of their search.
On the server (web api) I restrict the search using those two chars and all is well, i.e. a subset is returned and correctly shown and further filtered if I carry on typing in the search.
However, I then retype a new search entry which is no longer firing back to the datasource so I am stuck with the data that was retrieved from the first query.
How do I go about this properly?
Thanks
Here is my test code:
public class AlbumsController : ApiController
{
HttpRequest _request = HttpContext.Current.Request;
// GET api/albums
public IEnumerable<Album> GetForAutoComplete()
{
string sw = _request["sw"] == null ? "" : _request["sw"].ToString();
var query = (from a in Albums.MyAlbums
where a.Title.ToLower().StartsWith(sw)
orderby a.Title
select a).ToArray();
return query;
}
and my javascript on the client is like this:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/api/Albums/GetForAutoComplete",
data: {
sw: function () {
return $("#albumSearch").data("kendoAutoComplete").value();
}
}
}
}
});
$("#albumSearch").kendoAutoComplete({
dataSource: dataSource,
dataTextField: "Title",
minLength: 2,
placeholder: "type in here.."
});
Set serverFiltering to true. The default is false, so it will only grab data once and assume that it now has all the data, and subsequent filtering is done on the client.
To have it re-send to the server every time, add this:
var dataSource = new kendo.data.DataSource({
serverFiltering: true, // <-- add this line.
transport: {
...
}
});
The code for selecting an European country while typing using kendo autocomplete from database as below:
$("#countries").kendoAutoComplete({
dataTextField: "yourfield",
filter: "startswith", // or you can use filter: "contains",
minLength: 3, //what ever you want. In my case its 0.
placeholder: "Select country...",
dataSource: {
type: "get",
serverFiltering: true, //or can also make it false
transport: {
read: {
url: "/yourController/yourAction",
datatype: "json"
}
}
}
});
It works fine for me.

Resources