Pass parameter as query string to kendo datasource create method - kendo-ui

Scenario : consider we have two view-models use same data source masterDataSource, and we want to add a detail entity to master entity.
Question : how would you pass masterId as query string to the create method of datasource from those view-models:
var masterDataSource = new kendo.data.DataSource({
transport: {
create: {
url: function() {
return "/api/master/addItem?masterId=" + masterId;//<-- How to pass masterId form view-models
},
dataType: "json",
type: "POST"
},
},
schema: {
model: {
id: "id"
}
}
}

I found this solution:
var dynamicUrl = "/api/master/addItem?masterId=" + masterId;
masterDataSource.transport.options.read.url = dynamicUrl;

Related

How does the model structure look like for Kendo TreeView, to bind remote data?

How does the model structure look like for Kendo TreeView, to bind remote data
We have a tree displaying system locations which have hierarchical structure. We use the following code:
C# code:
[HttpPost]
public async Task<ActionResult> GetChildrenAsync(long? parentId)
{
//retrieving location's children by parentId
//DTO has ChildrenCount field that shows how many children has any particular location
return new JsonResult
{
Data = locations.Select(x => new
{
LocationId = x.Id,
Name = x.Name,
HasChildren = x.ChildrenCount > 0
}),
MaxJsonLength = Int32.MaxValue
};
}
JS code:
var locationDataSource = new kendo.data.HierarchicalDataSource({
transport: {
type: "json",
read: {
url: "#Url.Action("GetChildren", "Location")",
type: "POST"
},
parameterMap: function (data) {
return { parentId: data.LocationId };
}
},
schema: {
model: {
id: "LocationId",
hasChildren: "HasChildren"
}
}
});
var kendoTree = $("#location-tree").kendoTreeView({
dataSource: locationDataSource,
dataTextField: "Name"
});

Kendo Datasource not sending string to Controller

I am creating a CRUD application, My application is getting a string from from a Kendo input box, and will need to send it to my controller which is expecting a string that I am getting from my Jquery call. However, the string is not getting to my controller. I have tried various ways and I am not able to send it through my Transport. I have put break point and I can confirm that the value is being picked up in my Kendo Observable.
My Datasource
var client = new kendo.data.DataSource({
transport: {
read: {
url: "Client/SearchClient",
contentType: "application/json; charset=utf-8",
dataType: "json",
},
My Controller
public ActionResult SearchClient()
{
return View();
}
[HttpPost]
public ActionResult SearchClient(string name)
{
Repo repo = new Repo();
var result = repo.GetClient();
return Json(new
{
list = result,
count = result.Count
}, JsonRequestBehavior.AllowGet);
}
This is my Kendo Observable
var viewModel = kendo.observable({
client: {
clientName: "",
clientNumber: "",
clientType: "",
},
dropdownlist: ["HCC", "Tax", "Audit", "Advisory"],
create: function (e) {
var userRequest = $("#clientname").val();
if (userRequest) {
client.read(userRequest);
}
if (!userRequest)
alert("Please Enter Client Name")
}
});
Search Client method wants POST, not GET? The default will be GET. Either change your api method to use HttpGet, or change the transport to method: "post" for read.
var client = new kendo.data.DataSource({
transport: {
read: {
url: "Client/SearchClient",
contentType: "application/json; charset=utf-8",
dataType: "json",
method: "post"
},

Kendo UI, Grid, modify Data before send

Is it possible to access and modify data in Kendo UI grid before updating?
Below is an example to illustrate what I need. The options.data contains the sent data but it is already formatted in string "models=%B7%22Id22%.... etc" not really convenient form.
dataSource = new kendo.data.DataSource({
transport: {
read: {
...
},
update: {
url: baseURL + "update",
beforeSend: function(xhr, options){
xhr.setRequestHeader('API-KEY', apikey );
var modifiedData = doSomething(options.data);
return modifiedData;
},
dataType: "json",
method: "POST",
dataFilter: function(data){
... some data recieved modification
return JSON.stringify(somedata);
},
complete: function(e) {
....
}
},
You should be able to use the parameterMap function, check the type for "update" and change the options.data anyway you want.
parameterMap: function(options, type) {
if(type === "update") {
options.someProperty = "somenewvalue";
}
return kendo.data.transports.odata.parameterMap(options, type);
}

Change data sent to server for related data on update using kendo.datasource?

I am using the $expand to get related data which works fine but I need to change the data that is sent back
to the server when the data is updated
Example if my Server Side Data Model contains two entities
Contact
ID: number
firstName: string
middleName: string
lastname: string
ContactType: ContactType n-1
ContactType
ID: nubmer
name: string
ContactCollection: ContactType 1-n
Here is my datasource code
function GetContactDS(){
var MyModel = kendo.data.Model.define({
id: "ID",
fields: {
__KEY: { type: "string" },
__STAMP: { type: "number" },
ID: { editable: false, nullable: true },
firstName: { type: "string" },
middleName: { type: "string" },
lastName: { type: "string" }
},
});
var crudServiceBaseUrl = "http://127.0.0.1:8081/cors/Contact";
var MyDataSource = new kendo.data.DataSource({
transport: {
read: function(options) {
$.ajax( {
url: crudServiceBaseUrl + '/?$expand=ContactType',
dataType: "json",
data: options.data,
success: function(result) {
options.success(result);
}
});
},
update: function(options) {
$.ajax( {
url: crudServiceBaseUrl + "/?$method=update",
type: "POST",
dataType: "json",
data: kendo.stringify(options.data.models),
success: function(result) {
// notify the DataSource that the operation is complete
options.success(result);
}
});
},
destroy: {
url: crudServiceBaseUrl + "/?$method=delete",
type: "GET"
},
create: {
url: crudServiceBaseUrl + "/?$method=update",
dataType: "json",
type: "POST"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return JSON.stringify({"__ENTITIES": options.models});
}
}
},
batch: true,
pageSize: 30,
schema: {
model: MyModel,
data: "__ENTITIES"
}
});
return MyDataSource;
}
The read request returns this data
{"__entityModel":"Contact","__COUNT":1,"__SENT":1,"__FIRST":0,"__ENTITIES":[{"__KEY":"7","__STAMP":9,"ID":7,"firstName":"jay","middleName":"a","lastName":"blue","ContactType":{"__KEY":"2","__STAMP":4,"ID":2,"name":"Home","contactCollection":{"__deferred":{"uri":"/rest/ContactType(2)/contactCollection?$expand=contactCollection"}}}}]}
Here is the code calling read and binding to grid
var ContactDS = GetContactDS();
$("#grid").kendoGrid({
selectable: "row",
filterable: true,
pageable: true,
sortable: true,
change: function(){
datamodel = this.dataItem(this.select());
ID = datamodel.ID
},
dataSource: ContactDS,
columns: [
{ field: "ID" },
{ field: "firstName" },
{ field: "middleName" },
{ field: "lastName" },
{field: "ContactType.name"}
]
});
Which works fine I am getting the expanded info for ContactType in my datasource and it binds to a grid fine.
Now I want to update the after it the selected data row is read into a form, reading the data into the form works fine.
The problem is sending the update back to the server which expects a slightly different format for the related entity ContactType
It only needs the changed value of "__Key" to update
Here is my update function:
$("#update").click(function () {
datamodel.set("firstName", $("#firstName").val());
datamodel.set("lastName", $("#lastName").val());
datamodel.set("middleName", $("#middleName").val());
// datamodel.set("ContactType.__KEY",3);
ContactDS.sync();
Here is the data that the server expects
{ "__ENTITIES": [{"__KEY":"7","__STAMP":14,"firstName":"jay","middleName":"a","lastName":"red","ContactType":{"__KEY":"2"}}]}
Here is what kendo.datasource is sending
[{"__KEY":"7","__STAMP":12,"ID":7,"firstName":"jay","middleName":"a","lastName":"blue","ContactType":{"__KEY":"3","__STAMP":2,"ID":3,"name":"Work","contactCollection":{"__deferred":{"uri":"/rest/ContactType(3)/contactCollection?$expand=contactCollection"}}}}]
So how do I either reformat the data or define my model or datasource options to make sure that the extra ContactType fields are removed just leaving the updated "_KEY:" as well as wrapping the whole request in { "_ENTITIES":}
Thanks for any help!
Dan
You could try to use the parameterMap function to format the data in the way you need.
I think I found the answer from this post
It explains a little more on using parameterMap. If you look at the kendoui docs on parameterMap it seems to indicate that this is only for managing parameters like
pageIndex,size,orderBy ect. But from the above post it shows you how to delete a related entity or you can just delete or modify the fields of an entity or related entity
Example I can delete just the ContactTypeID of the related entity ContactType
parameterMap: function(options, operation) {
if (operation == "create") {
return JSON.stringify({"__ENTITIES": options.models});
}
else if (operation == "update") {
debugger;
delete options.models[0].ContactType.ID;
return JSON.stringify({"__ENTITIES": options.models});
}
}
Still have some work to do but I think this will get me there
Thanks Pechka for your help

Kendo UI DataSource Issue passing parameters to service

I'm using Kendo UI Grid + DataSource and I'm facing some issues interacting with my service:
We have a service which should be called as follows:
/find?criteria[0].FieldName=Name&criteria[0].Value=Test&criteria[1].FieldName=Description&criteria[1].Value=MyDescription
How I can pass the parameters as such to my service from my datasource?
you have to use the parameterMap function like this:
var data = kendo.data.DataSource({
transport: {
// these are passed to $.ajax()
read: {
url: "/find",
dataType: 'json',
type: 'GET',
cache: false
},
update: {
// ...
},
destroy: {
// ...
},
create: {
// ...
},
//
parameterMap: function(options, type) {
// edit VARS passed to service here!
if (type === 'read') {
return {
'criteria[0].FieldName': options.name,
'criteria[0].Value': options.value
// ...
};
}
}
},
schema: {
model: MyModel,
type: 'json',
parse: function(response) {
// edit VARS coming from the server here!
// ...
return response;
}
}
});
If you are using client side Json binding. check: dataSource->transport->parameterMap property.
such as:
$(function () {
$("#grid").kendoGrid({
.....
dataSource: {
....
transport: {
parameterMap: function (data, operation) {
if (operation != "read") {
.....
return result;
} else {
//data sample: {"take":10,"skip":0,"page":1,"pageSize":10}
//alert(JSON.stringify(data)); //Need to insert custom parameters into data object here for read method routing. so, reconstruct this object.
data.CustomParameter1 = "#Model.Parameter1"; // Got value from MVC view model.
data.CustomParameter2 = "#Model.Parameter2"; // Got value from MVC view model.
return JSON.stringify(data); // Here using post. MVC controller action need "HttpPost"
}
}
}
}
MVC controller:
[HttpPost]
public ActionResult Read(int CustomParameter1, int CustomParameter2, int take, int skip, IEnumerable<Kendo.Mvc.Grid.CRUD.Models.Sort> sort, Kendo.Mvc.Grid.CRUD.Models.Filter filter)
{
.....
}
Corporated project sample in:
http://www.telerik.com/support/code-library/grid-bound-to-asp-net-mvc-action-methods---crud-operations

Resources