How to load kendo grid data with ajax call - kendo-ui

How to load kendo grid data with ajax call using dataSource.data method. I have tried following but it is not working. $('#AAMaintenance').data('kendoGrid').dataSource.data(result);
function filterOnSubmit() {
var data = {};
data["ExaminerNo"] = $("#txtExaminerNo").val();
data["ExaminerName"] = $("#txtExaminerName").val();
$.ajax(
{
type: 'POST',
url: '#Url.Action("GetFilteredAAMaintenanceDetails", "AAMaintenance")',
contentType: "application/json",
dataType: 'json',
data: JSON.stringify({ aaMaintenanceFilter: data }),
success: function (result) {
$('#AAMaintenance').data('kendoGrid').dataSource.data(result);
$('#AAMaintenance').data('kendoGrid').refresh();
}
});
}

Assuming that the dataSource hasn't been setup for the Kendo grid control prior to the ajax call to retrieve the data, you should instantiate this before setting it as the datasource:
var ds = new kendo.data.DataSource({
data: result
});
$("#AAMaintenance").data("kendoGrid").setDataSource(ds);
A few notes aside from this, and based on Telerik documentation:
If the result returned from the server is a complex object (unknown currently), you may need to look into schema.model.
Ensure that the column declaration field attributes match the names assigned to the object attributes you wish to display, for example note in this example how the field: "name" column matches the name attribute being added to the dataSource.

Related

Redraw datatables with search

I am using DataTables. I have added the below code when the page is loading and the table getting all data as expected.
var table = $('#expensesTable').DataTable({
responsive: true,
searchDelay: 500,
processing: true,
serverSide: true,
ajax: {
url: '/books/daybooks/datatable',
type: 'POST',
},
columns: [
{data: 'expense_id'},
{data: 'expense_date'},
{data: 'expense_description'},
{data: 'expense_amount'},
{data: 'vendor_name'},
],
});
Now, I have added a date range picker where it will search data in the server and response will be given back to query via Ajax.
$('#datepicker').on('apply.daterangepicker', function(ev, picker) {
var start = picker.startDate.format('YYYY-MM-DD');
var end = picker.endDate.format('YYYY-MM-DD');
jQuery.ajax({
type: "POST",
url: '/books/daybooks/datatable',
data: {start : start, end : end},
success: function(data)
{
console.log(data);
} // Success End
}); //AJAX End
});
Now i am getting all expected filter data as success, but now I need to redraw the table with newly got data after the filter of Ajax call.
if i use $('#expensesTable').DataTable().draw(); then it will do draw without filter,
So i can draw table with filter data?
Thanks in advance.
Instead of introducing a new ajax call (the jQuery ajax), you can re-use your existing DataTables ajax call when submitting your date range filter data.
To do this, you need to take the following steps:
(1) Update your DataTables ajax option:
ajax: {
url: '/books/daybooks/datatable',
type: 'POST',
data: function () {
return { "start": start, "end" end };
}
},
This data function allows you to dynamically assign values to your request. They will be added as standard URL-encoded form data, in the usual way for POST requests.
See here for more information. There are several different ways to use ajax.data. For example, if you were using serverSide processing (which you are not) then the above approach would not work correctly.
(2) To re-use your DataTables ajax call, you can use this:
table.ajax.reload();
See here for more information.
This replaces your jQuery ajax call:
var start;
var end;
$('#datepicker').on('apply.daterangepicker', function(ev, picker) {
start = picker.startDate.format('YYYY-MM-DD');
end = picker.endDate.format('YYYY-MM-DD');
table.ajax.reload();
});
When the table first loads (not using reload()), the filter values will be null.

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 pass the value of an HtmlHelper dropdown list in a javascript ajax call with onchange event?

I want to pass the Htmlhelper helper value of a dropdown in an ajax call
#Html.DropDownListFor(m => m.LanguageRouteName, (SelectList)ViewBag.LanguageEnum, new { #onchange = "submitform(event)", #class = "input-medium", #id = "languageEnum" })
i am trying to pass the event but i need all the values of HtmlHelper 'helper'. How do i get this value? Please Help
$('#languageEnum').Onchange(function(){
var ddl val=$('#languageEnum').val();
$.ajax({
type: "GET", //GET or POST or PUT or DELETE verb
url: ajaxUrl, // Location of the service
data: "ddldata:ddl", // dropdown data
dataType: "json", //Expected data format from server
success: function (json) {//On Successful service call
var result = json.name;
$("#dvAjax").html(result);
}
})
});

Unable to set Kendo UI Grid DataSource

I'm making an addition to a working Kendo UI grid to allow it to update based on an id passed in from a textbox. I'm calling my controller from the ajax, and everything works as expected until I try and create the kendo.data.DataSource() for my grid inside of the ajax success. The result looks as expected but anything I do to assign it to the data source does not seem to work. The data shows nothing and the grid comes up empty.
The model expected by the grid does match the one in my controller. I've looked at other questions and the kendo ui docs but I can't seem to figure out what I'm doing wrong... any help will be appreciated.
Ajax:
$.ajax({
type: "POST",
url: '#Url.Action("Search")',
data: JSON.stringify({ id: id }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
var grid = $("#Grid").data("kendoGrid");
var data = new kendo.data.DataSource(result);
grid.dataSource.data(data);
grid.refresh();
}
});
Controller:
public ActionResult Search([DataSourceRequest]DataSourceRequest request, string id)
{
IEnumerable<SearchModel> data = GetData(id);
return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
You are using the ToDataSourceResult() extension method on the server so you need to using the Data property of result to assign to the data property of the DataSource object you are creating on the client. Also, you should use the setDataSource method of the grid not grid.dataSource.data(). Lastly, you want to call the read() method of the dataSource grid property, not grid.Refresh().
$.ajax({
type: "POST",
url: '#Url.Action("Search")',
data: JSON.stringify({ id: id }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
var grid = $("#Grid").data("kendoGrid");
var dataSource = new kendo.data.DataSource({
data: result.Data
});
grid.setDataSource(dataSource);
grid.dataSource.read();
}
});
You are creating the DataSource incorrectly. Assuming the result of your AJAX call returns an array, you must then wrap it in an object with a data property that holds the array of data.
$.ajax({
// ...
success: function (result) {
var grid = $("#Grid").getKendoGrid();
var data = new kendo.data.DataSource({ data: result });
grid.dataSource.data(data);
grid.refresh();
}
});
The following is an alternative way to create a DataSource and allows passing in an array (unwrapped), a DataSource configuration object, or even a preexisting DataSource object.
var data = kendo.data.DataSource.create(obj);
This approach is preferable b/c it is more flexible.
I hope that helps!

kendoAutoComplete options like dataTextField?

I Have problem with my kendoAutoComplete i want to bind two fields to kendoAutoComplete, now I can bind one field name to dataTextField but for another field like id i dont have any other option, Following is my code
var alld="";
function getData(req) {
$.ajax({
url: 'BookingCity.asmx/GetAllCityBus',
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'json',
minLength: 1,
async: false,
cache: false,
data: "{'prefixText':'" + req + "'}",
success: function(response) {
alld = response.d;
},
error: function(xhr, status) {
alert("error");
}
});
}
$("#totext").kendoAutoComplete({
dataSource: {
read: getData($("#totext").attr("value")),
data: alld
},
minLength: 2,
placeholder: "Select city...",
dataTextField: "Name",
dataTextField:"Id"
});
You can use template to achieve this:
$("#totext").kendoAutoComplete({
template: "#=Name# #=Adress#",
//.. rest of the options
I think you might be looking for dataValueField:"Id"
NOTE:
dataValueField is not used in kendoAutoComplete (my apologies). It was on the demo page on the Kendo UI website by mistake. It seems a dropdownlist or combobox can be used instead.
This is assuming you need to return a value that corresponds with the dataTextField (like the Id).
You can read more about it on the Kendo UI Forums - DataValueField does exist ?
or see this relevant excerpt:
The autocomplete UI widget persists only the selected text. Actually the you can post only the content of the input element. This is the expected behavior. As to the demos, the "dataValueField" is left by mistake and we will fix that for the next release of KendoUI.
In order to achieve your goal, you will need to use dropdownlist or combobox, which persist the selected id.
Regards,
Georgi Krustev
the Telerik team
Why do you want to do this? You can only bind one field to the dataTextField property, so if you want to show two, just add an additional calculated field to your datasource that contains the concatenated values of both fields and bind to that.

Resources