Kendo Grid send extra parameters - kendo-ui

How can i send extra parameters on my GRID POST.
This is my tranport config:
transport: {
read: {
dataType: "json",
url: "/user/list",
type: "POST"
}
}
I need to send a dynamic extra information ( especial filters XD).
I will set a script variable before any submit on grid.
Any Help?

Question is discussed multiple times on the internet. You should use the Data function. Here is even more information. You can also pass the parameters directly to the read method of the dataSource.
$('#myGrid').data().kendoGrid.dataSource.read({foo:42})

You can add extra parameters using Data("addParameter")
#(Html.Kendo().Grid<Project.Models.UserModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(item => item.UserId).Title("UserId").Width(100);
columns.Bound(item => item.UserName).Title("UserName").Width(200);
})
.Sortable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(5)
.Read(read => read.Action("list", "user").Data("addParameter"))
)
<script>
function addParameter()
{
return {
UserId: 10 //Your value here
};
}
</script>

Here is another alternative to send parameters to the AJAX call, and also to log the Request and Response.
read: function (options) {
var jsonData = {
"ID": $('#ID').val(),
"ObjectType": $('#dropObjectType :selected').val()
};
console.log("REQ: " + JSON.stringify(jsonData));
$.ajax({
type: "POST",
url: "/api/internal/SomeService",
data: jsonData,
success: function (result) {
console.log("RES: " + JSON.parse(JSON.stringify(result)));
You can also send the above jsonData in this way:
$("#grid").data("kendoGrid").dataSource.read(jsonData);
And assign it to the data: (and log it):
read: function (options) {
console.log("REQ: " + JSON.stringify(options.data));
$.ajax({
type: "POST",
url: "/api/internal/SomeService",
data: options.data,

Related

How to modify kendo grid's edited value before posting to server

I have a Kendo grid that is enabled for InCell editing. The Grid is also configured for CURD operation.
So whenever there is a change in the grid row. The user has to click SaveChanges command button to save changes. The grid will post collection of row model to the server.
#(Html.Kendo().Grid<mymodel>()
.Name("mygrid")
.Columns(columns =>
{
//columns here
columns.Command(command => command.Destroy()).Width(100);
})
.ToolBar(toolbar =>
{
toolbar.Create();
toolbar.Save();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Pageable()
.Navigatable()
.Sortable()
.Scrollable()
.Filterable()
.AutoBind(true)
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.PageSize(20)
.ServerOperation(false)
.Model(model =>
{
model.Id("Id");
var f = model.Field("Id", typeof(int));
f.Editable(false);
})
.Model(model =>
{
model.Id("Id");
var f = model.Field("Id", typeof(int));
f.Editable(false);
})
.Create("Create", "Test")
.Read("Get", "Test")
.Update("Update", "Test")
.Destroy("Delete", "Test")
))
When user clicks SaveChanges, I want to modify the row model before posting to the server.
Grid has SaveChanges event which get fire every time user click SaveChanges
$(function(){
var kendoGrid = $("#mygrid").getKendoGrid();
kendoGrid.bind("saveChanges", function (e) {
var datasource = kendoGrid.dataSource;
// how do I update data before posting it to the server here
});
How do I update model that is about to post to server? Is SaveChanges event the correct event to handle this scenario?
The Save changes event is the one you want. Since your using mvc you can also set the event up with the rest of your grid by doing .Events(e=>e.SaveChanges"onGridSave"). Then onGridSave becomes a javascript function you define.
The .Events() goes at the same level as .Pageable() or .Navigatable().
Then in your javascript function you could do something like this:
function onGridSave(e){
e.sender.dataSource._data[0].PropertyName = "new value/data manipulation"
}
PropertyName being the model property you want to modify. The _data[0] refers to the first element in your dataSource. You may need to iterate or adjust the index to reach the row you want to modify.
Rows that have been modified will have a ._data[0].dirty property set to true. Only elements with dirty set to true will be passed to your controller.
I im not familiar with kendo for asp.net so i cannot give you exact answer, but usually you can intercept, or add, or modify data in parameterMap before sending, for example:
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(data, type) {
switch (type) {
case 'read':
let request = {};
request.page = data.page - 1;
request.page_size = data.pageSize;
request.sort = data.sort;
request.filter = data.filter;
return JSON.stringify(request);
case 'destroy':
return kendo.stringify(data.models);
case 'update':
console.log("Data that that will be sent for updating: ", data.models);
return kendo.stringify(data.models);
default:
break;
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
}
}
}
});
You can check this official example, i only changed ProductName on first object that will be sent on update click:
Batch update intercept before sending
I hope you can salvage something from this, gl!

How to remove Knockout.js ObservableArray-object after ajax call

I'm trying to remove an object from an ObservableArray after an ajax-call. It works with the '.pop' function, but not when I'm using the custom knockout.js '.remove'-function.
If I move the call to the '.remove' function outside the ajax-complete function, '.remove' does work. But I would really rather have it inside the '.complete'.
Can anyone spot what I'm doing wrong?
This doesn't work:
self.removeItem = function(data) {
$.ajax({
type: 'POST',
url:'/echo/js/?js=hello%20world!',
dataType: 'json',
contentType: 'application/json',
data: null
}).complete(function (item,data) {
self.Items.remove(data);
});
};
I made a jsfiddle to demonstrate: http://jsfiddle.net/6oe6dn7n/1/
My view-model looks like so:
var data = {
Name: "Test",
Items: ["One", "Two", "Three"]
};
function ViewModel(data) {
var self = this;
self.Items = ko.observableArray(ko.utils.arrayMap(data.Items,
function(item) {
return { value: ko.observable(item) };
}));
self.removeItem = function(data) {
$.ajax({
type: 'POST',
url:'/echo/js/?js=hello%20world!',
dataType: 'json',
contentType: 'application/json',
data: null
}).complete(function (item,data) {
// This doesn't affect the observableArray.
// 'self.Items.pop(data) does, however.
self.Items.remove(data);
});
};
}
And my HTML looks like so:
<div>
<table>
<tbody data-bind="template: { name: 'itemTemplate', foreach: Items }"></tbody>
</table>
</div>
<script type="text/html" id="itemTemplate">
<tr>
<td>
<input data-bind="value: value" />
Remove Item
</td>
</tr>
</script>
You have replaced "data" variable object in the context of response handler:
was:
self.removeItem = function(data) { // <- data
$.ajax({
type: 'POST',
url:'/echo/js/?js=hello%20world!',
dataType: 'json',
contentType: 'application/json',
data: null
}).complete(function (item, data) { // <- another data overrides upper data
// This doesn't affect the observableArray.
// 'self.Items.pop(data) does, however.
self.Items.remove(data); // <- what data to use???
});
};
changed:
self.removeItem = function(data) {
$.ajax({
type: 'POST',
url:'/echo/js/?js=hello%20world!',
dataType: 'json',
contentType: 'application/json',
data: null
}).complete(function (item, data1) { // another data - data1
// This doesn't affect the observableArray.
// 'self.Items.pop(data) does, however.
self.Items.remove(data);
});
};
I've updated the fiddle, it works for me - at least removes items.
You need to use the data variable that is passed into removeItem. Instead you override it, by using the textStatus variable of the complete callback. Like so:
self.removeItem = function(data) {
$.ajax({
type: 'POST',
url:'/echo/js/?js=hello%20world!',
dataType: 'json',
contentType: 'application/json',
data: null
}).complete(function (item) {
self.Items.remove(data);
});
};
The reason self.Items.pop(data) worked is because .pop doesn't actually take any parameters. So the data you passed in is never used, and the call is just popping the array. The second parameter in the complete callback method is by default a textStatus response.
From the documentation:
http://api.jquery.com/jQuery.ajax/
complete
Type: Function( jqXHR jqXHR, String textStatus )
A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "nocontent", "error", "timeout", "abort", or "parsererror").

Populating a kendo multiselect with ajax data

I am using a kendo multiselect widget for users to select different values pulled from the database via an ajax call. The ajax call takes one parameter, searchValue, which will narrow down the returned data. Here is my controller:
[HttpPost]
public JsonResult ProfitabilitySearch(string searchValue)
{
return Json(InventoryDataAccess.ProfitabilitySearch(searchValue));
}
1) How do you get the value from the text box to use as your searchValue? I commented the area in question below.
Here is my dataSource:
var searchDataSource = new kendo.data.DataSource({
transport: {
read: function () {
$.ajax({
type: 'POST',
url: Firm.ProfitabilitySearchURL,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
//'SuperClient' is test data to see if it works, but what do i
//need to make searchValue = what I type?
data: JSON.stringify({ searchValue: 'SuperClient'}),
success: function (data) {
return data.RESULT;
}
});
}
},
group: { field: 'category' },
serverFiltering: true
});
And here is where I create the multiselect widget:
var TKSearch = $("#TKSearch").kendoMultiSelect({
dataSource: searchDataSource,
autoBind: false,
minLength: 3,
placeholder: 'Search Timekeepers...',
dataTextField: 'label',
dataTextValue: 'value',
delay: 200
}).data("kendoMultiSelect");
I'm not sure if this will help, but here is the structure of the json that is returned from the ajax call:
{"label":"SUNFLOWER REALTY CORP. (023932)","value":"023932","category":"RC"}
Solving the first question above may answer my second question so I will wait to ask that until after.
You can use functions for the request parameters.
var searchDataSource = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: 'POST',
url: Firm.ProfitabilitySearchURL,
contentType: 'application/json; charset=utf-8',
data: {
searchValue: function () {
// better: use a model property instead of this
return $("#TKSearch").data('kendoMaskedTextBox').value();
}
},
success: function (data) {
options.success(data.RESULT);
}
});
}
},
group: { field: 'category' },
serverFiltering: true
});
Notes
This really should be a GET request. Use POST for requests that actually change data on the server and GET for requests that merely retrieve data from the server.
You do not have to JSON.stringify() yourself. jQuery does that transparently.
Specifying dataType is completely superfluous, jQuery will figure this out from the response headers.
Reading the input value via jQuery is not clean. Use the data-bound model property instead.
The callback invocation (options.success())
This sample lacks HTTP error handling, you must add that.

How to dynamically pass data parameter in a jquery ajax call (multiple arrays of data)

I have this ajax code:
return $.ajax({
type: "POST",
url: "somefile.php",
cache:false,
data: { "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() },
dataType:"json",
success: function(data){
alert("success");
}
This works fine, but I need to pass the data parameter dynamically. For now I need the above data parameter content and a single string.
How do I pass this dynamically? / How do I store it in a variable and pass it to the "data:" field?
{ "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() }
I tried JSON.stringify I I couldn't get it to work probably due to the data being an array.
The year and genre arrays are coming directly from the jquery drop down menu. It is selected like by it's #id like so "$("#yearFilter")". This is the select form element.
<select multiple="multiple" name="yearFilter[]" class="filterChange" id="yearFilter">
What I need at the base level is:
var someData = "";
if(...){
someData = { "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() };
}
else if(...){
someData = "sampleString";
}
And in ajax call:
...
data: someData,
...
I think I have an idea what you want but post has been overly complicated by extraneous issues like json stringify . Here's a function that could be used in several places eleswhere in your code to make one type of AJAX call or another.
You would then perhaps have several buttons and call the function within handlers for each type of button and change the argument passed to function
doAjax('someval');/* use in button 1*/
doAjax('someOtherval');/* use in button 2*/
function doAjax(arg) {
var someData = "";
if (arg == 'someval') {
someData = {
"yfilter": $("#yearFilter").val(),
"gfilter": $("#genreFilter").val()
};
} else {
someData = "sampleString";
}
$.ajax({
type: "POST",
url: "somefile.php",
cache: false,
data: someData,
dataType: "json",
success: function(data) {
if (arg == 'someval') {
alert("success 1");
} else {
alert("success 2");
}
}
})
}
Hope I've understood what you're asking for.
You could do something like this:
var parameters = {};
if (...) {
parameters = $("#yearFilter").serializeArray();
}
if () {
parameters = $("#genreFilter").serializeArray();
}
and then replace the line:
parameters: { "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() },
with:
data: parameters,
JSON type should be best option for dynamically data. push whatever data you wish to inside json like shown below, Hence create your json dynamically and send as ajax data.
var employees = {
accounting: [],
dept: "HR"
};
employees.accounting.push({
"firstName" : item.firstName,
"lastName" : item.lastName,
"age" : item.age
});
$.ajax({
url: POSTURL,
type: 'POST',
dataType: 'json',
data : employees,
contentType: 'application/json; charset=utf-8',
success: function (results)
{
},
error: function (results)
{
jQuery.error(String.format("Status Code: {0}, ", results.status, results.statusText));
}
});
Try it:
someData = JSON.stringify({ yfilter: $("#yearFilter").val(), gfilter: $("#genreFilter").val() });
It will work.

how do you make ajax data key dynamic in jquery?

I'm trying to make my inline edit to be dynamic so it will just depend on some data- attributes from my markup so here's the code for now:
$(".inline-edit").editable(
function(value, settings) {
var editableField = $(this);
$.ajax({
type: 'PUT',
url: editableField.attr('data-href'),
dataType: 'html',
success: function(html) {
editableField.parents('.replaceable').replaceWith(html);
},
data: { 'regression_test_environment[name]' : value }
});
return(value);
},
{
event: 'click',
width: '80%',
height: '20',
submit : 'OK'
}
)
i want the name in regression_test_environment[name] to be editableField.attr('data-column-name') but it always fails in compiling because it keeps taking the key as a string. I tried making a variable after the editable field variable assignment and building the string as a different variable but it doesn't want to evaluate the key as a function.
Is there a way to do this? or am i stuck in creating a separate .editable call for each of my editable fields?
You may try like this:
var name = editableField.data('column-name');
var values = { };
values['regression_test_environment[' + name + ']'] = value;
$.ajax({
type: 'PUT',
url: editableField.data('href'),
dataType: 'html',
data: values,
success: function(html) {
editableField.parents('.replaceable').replaceWith(html);
}
});
Better, less confusing answer:
var data = {};
data[thisField] = $(this).text();
$.ajax({
data: data
});
Best is to pass dynamic values by serializing it :
var data = $('#formid').serialize(); // serialize all the data in the form
$.ajax({
url: 'test.php', // php script to retern json encoded string
data: data, // serialized data to send on server
...
});

Resources