Invoking Page Refresh from Kendo Grid Update - kendo-ui

I am using a Kendo-grid with inline editing Let's call this Grid3. The Grid is displaying a list of items from a referenced property of the page's view model. When an item on the grid has been saved, I would like to invoke a complete page refresh (or a refresh two other grids, Grid1 and Grid2 on the page). The reason is that when an items has been updated in the grid, values displayed in other grids are affected.
Any ideas?

Call datasource.read() at those grids you want to refresh.
$("#grid3").kendoGrid({
dataSource : dataSource,
save: function(e) {
grid1.dataSource.read();
grid2.dataSource.read();
}
}
Alternatively place the grid.datasource.read() call into your datasource complete.
var dataSource = new kendo.data.DataSource({
transport: {
update: {
complete: function (jqXhr, textStatus) {
grid1.dataSource.read();
grid2.dataSource.read();
}
}
}
});

This can be accomplished using the RequestEnd event.
The Kendo Grid declaration would have something like:
.DataSource(datasource => datasource
.Ajax()
.Model(model => model.Id(fi => fi.Id))
.Read(read => read.Action("Buildings_ReadForecast", "Plan", new {buildingId = Model.BuildingID}))
.Events(events => events.Error("error_handler"))
.Events(events => events.RequestEnd("OnRequestEnd_Grid"))
Then create the javascript method like:
function OnRequestEnd_Grid(e) {
if (e.type === "update") {
var forecastgrid = $('#ForecastGrid').data('kendoGrid');
var planGrid = $('#PlanGrid').data('kendoGrid');
planGrid.dataSource.read();
forecastgrid.dataSource.read();
}
}
That's it!

Related

Telerik/ Kendo MVC Grid, Load grid on demand, not on page load

i found a couple examples on how to do this, and none of them are working for me.
Here is my Telerik MVC grid:
#(Html.Kendo().Grid<PlayerStatsViewModel>()
.Name("PlayerStats")
.Columns(columns =>
{
columns.Bound(o => o.PlayerId);
columns.Bound(o => o.FirstName);
})
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => model.Id(p => p.PlayerId))
.Read(read => read.Action("PlayerStats_Read_Bound", "Contest").Data("getPlayerId"))
).AutoBind(false)
)
Open modal with my grid
I set autobind(false) which prevents page load. After a user clicks a link i open a modal with my grid, and need to pass in a parameter.
// open modal
$(document).on("click", "#openStatsModal", function () {
playerId = $(this).data('id'); // get parameter from click
loadPlayerStats();
});
function getPlayerId() {
return {
playerId: playerId
}
}
Make ajax call?
My click method works and i get my player id. Then i try and make my grid call.
function loadPlayerStats() {
var grid = $("#PlayerStats").data("playerStats");
alert(grid); // returns undefined
//grid.ajaxRequest(); this didnt work either
grid.dataSource.read(); // Cannot read property 'dataSource' of undefined
}
Action method
Never gets called unless i turn off autobind
public ActionResult PlayerStats_Read_Bound([DataSourceRequest]DataSourceRequest request, int playerId)
{
// some code
return Json(result)
}
Just try:
var grid = $("#PlayerStats").data("kendoGrid");
and then:
grid.dataSource.read();

kendo ui multiselect remove delete action

How can i restrict users from deleting the already saved items in the Multi select widget. Users should not be able to delete existing values but can add or remove the new values.
The solution i tried was on databound remove the delete icon like below. It gets deleted but comes back after the call executes the databound method.
Any ideas?
onDataBound: function (e) {
e.preventDefault();
$(e.sender.tagList).find("li span.k-delete").remove();
}
This is the code in the view which calls the above js function on databound
#(Html.Kendo().MultiSelectFor(x => x.Documents)
.DataTextField("Description")
.DataValueField("Code")
.Placeholder("Select Attachment...")
.AutoBind(false)
.DataSource(source => source.Read(read => read.Action("GetCustomerDocuments", "CustomerRequest")).ServerFiltering(true))
.HtmlAttributes(new {style = "width:400px;"})
.Events(e => e.DataBound("onDataBound"))
)
Have your tried applying the same method on the change event as on the databound event?
Razor:
.Events(e => e.Change("onChange"))
Javascript:
onChange: function (e) {
e.preventDefault();
$(e.sender.tagList).find("li span.k-delete").remove();
}

How do I prevent the cancel event from changing my grid row color?

I search for data and then bind to my grid. In the grid's databound event, I change the row background color according to the cell's value. This works OK. But when I click the Edit button in the grid and then click the Cancel button, the grid no longer has the background color set. I tried to call the databound event in the Cancel event, but it does not work. How do I prevent the Cancel Event from changing my grid color?
grid
#(Html.Kendo().Grid(Model)
.Name("mygrid")
.Events(e=>e.DataBound("dataBound"))
.Columns(columns =>
{
columns.Bound(p =>p.StudentName).Title("StudentName");
columns.Command(command =>
{
command.Edit().UpdateText("Edit");
command.Destroy().Text("Delete");
}).Width(160);
})
.Editable(editable => editable.Mode(GridEditMode.PopUp)
.TemplateName("SudentEditor")
.Window(configurator=>configurator.Width(500)
.Title("EditStudent")))
.Scrollable()
.Events(events=>events.Cancel("onCancel"))
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Model(model =>
{
model.Id(p => p.Id);
})
.Read(read => read.Action("GetStudentForGrid", "Student"))
.Create(create=>create.Action("CreateSudent","Equipment"))
.Update(update => update.Action("UpdateStudent", "Student"))
.Destroy(destory=>destory.Action("DestroyStudent","Student"))
.Events(events => events.Error("error_handler"))
))
databound event
//change grid color
function dataBound(e) {
$("#mygrid tbody tr").each(function(i) {
$(this).find("td:lt(9)").css("backgroundColor", '#000000');
});
}
cancel event
//I try to call preventDefault event and close the PopUp window
//,but the background is still grey
function onCancel(e) {
//e.preventDefault();
//e.container.parent().css("display", "none");
// e.sender.clearSelection();
dataBound();
}
Just refresh the grid in the cancel event. It will fire the onDataBound event again. I had the same issue and resolved it like this:
function onCancel(e) {
$("#GridName").data("kendoGrid").refresh();
}
//change grid color
function dataBound(e) {
$("#mygrid tbody tr").each(function(i) {
$(this).find("td:lt(9)").css("backgroundColor", '#000000');
});
}
You can use grid.cancelRow() in the cancel enent,and then refresh the grid.
If you don't want to refresh the grid but run code after the event has finished instead, you can use a setTimeout() in the cancel event.
function onGridCancel(e){
setTimeout(function() {
colorMyRowsBeutifully();
}, 0);
}
See this answer from Telerik:
https://www.telerik.com/forums/grid-cancel-event
I also ran into this problem and the solutions from above didn't work for me.
But I found another solution that did the trick, to use the Edit event of the Grid to attach event handler to the Deactivate event of the Window.
Grid events:
.Events(e => {
e.DataBound("onDataBound");
e.Edit("onEdit");
})
Grid event handlers:
function onDataBound(e) {
//Conditional formatting on DataBound
formatGridRows();
}
function onEdit(e) {
//Bind deactivate event to the Popup window
e.container.data("kendoWindow").bind("deactivate", function () {
formatGridRows();
})
}
function formatGridRows() {
$("#Grid tbody tr").each(function () {
grid = $("#Grid").data("kendoGrid");
dataItem = grid.dataItem($(this));
//Conditionally format the current row
if (dataItem.Discontinued) {
$(this).find(":nth-child(3):first").css("background", "red");
}
})
}
Here's the source:
http://www.telerik.com/forums/cancel-popup-clears-grid-background-color

Kendo Grid Callback function after sortable event fire

I am using Kendo Grid to sorting table data. I want an event which fire after sorting is completed. i want like below code.
$("#innergrid").kendoGrid({
sortable: true,
Aftersorting : function(event) { alert('sorting is done') }
});
You can use the change event of the dataSource (will be created automatically when you init the grid). Check this: http://jsbin.com/buten/1/edit
I am not sure is there any event which can be triggered after sorting but you can do this
********************Grid************************
#(Html.Kendo().Grid<>()
.Name("CompanyServicesGrid")
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Events(events => e.RequestEnd("onRequestEnd"))
)
**************************Javascript********************
function onRequestEnd(e)
{
if (e.type == "read"){
if(e.sender_sort=="ColumnName")
alert("sorting is done")
}
}
have a look at this as well
onRequestEnd-Link
OnComplete-Link

Reloading/refreshing Kendo Grid

How to reload or refresh a Kendo Grid using Javascript?
It is often required to reload or refresh a grid after sometime or after a user action.
You can use
$('#GridName').data('kendoGrid').dataSource.read(); <!-- first reload data source -->
$('#GridName').data('kendoGrid').refresh(); <!-- refresh current UI -->
I never do refresh.
$('#GridName').data('kendoGrid').dataSource.read();
alone works for me all the time.
In a recent project, I had to update the Kendo UI Grid based on some calls, that were happening on some dropdown selects. Here is what I ended up using:
$.ajax({
url: '/api/....',
data: { myIDSArray: javascriptArrayOfIDs },
traditional: true,
success: function(result) {
searchResults = result;
}
}).done(function() {
var dataSource = new kendo.data.DataSource({ data: searchResults });
var grid = $('#myKendoGrid').data("kendoGrid");
dataSource.read();
grid.setDataSource(dataSource);
});
Hopefully this will save you some time.
$('#GridName').data('kendoGrid').dataSource.read();
$('#GridName').data('kendoGrid').refresh();
Not a single one of these answers gets the fact that read returns a promise, which means you can wait for the data to load before calling refresh.
$('#GridId').data('kendoGrid').dataSource.read().then(function() {
$('#GridId').data('kendoGrid').refresh();
});
This is unnecessary if your data grab is instant/synchronous, but more than likely it's coming from an endpoint that won't return immediately.
If you do not want to have a reference to the grid in the handler, you can use this code:
$(".k-pager-refresh").trigger('click');
This will refresh the grid, if there is a refresh button.
The button can be enabled like so:
[MVC GRID DECLARATION].Pageable(p=> p.Refresh(true))
Actually, they are different:
$('#GridName').data('kendoGrid').dataSource.read() refreshes the uid attributes of the table row
$('#GridName').data('kendoGrid').refresh() leaves the same uid
What you have to do is just add an event
.Events(events => events.Sync("KendoGridRefresh"))
in your kendoGrid binding code.No need to write the refresh code in ajax result.
#(Html.Kendo().Grid<Models.DocumentDetail>().Name("document")
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Model(model => model.Id(m => m.Id))
.Events(events => events.Sync("KendoGridRefresh"))
)
.Columns(columns =>
{
columns.Bound(c => c.Id).Hidden();
columns.Bound(c => c.UserName).Title(#Resources.Resource.lblAddedBy);
}).Events(e => e.DataBound("onRowBound"))
.ToolBar(toolbar => toolbar.Create().Text(#Resources.Resource.lblNewDocument))
.Sortable()
.HtmlAttributes(new { style = "height:260px" })
)
And you can add the following Global function in any of your .js file. so, you can call it for all the kendo grids in your project to refresh the kendoGrid.
function KendoGridRefresh() {
var grid = $('#document').data('kendoGrid');
grid.dataSource.read();
}
In my case I had a custom url to go to each time; though the schema of the result would remain the same.
I used the following:
var searchResults = null;
$.ajax({
url: http://myhost/context/resource,
dataType: "json",
success: function (result, textStatus, jqXHR) {
//massage results and store in searchResults
searchResults = massageData(result);
}
}).done(function() {
//Kendo grid stuff
var dataSource = new kendo.data.DataSource({ data: searchResults });
var grid = $('#doc-list-grid').data('kendoGrid');
dataSource.read();
grid.setDataSource(dataSource);
});
I used Jquery .ajax to get data. In order to reload the data into current grid, I need to do the following:
.success (function (result){
$("#grid").data("kendoGrid").dataSource.data(result.data);
})
You can use the below lines
$('#GridName').data('kendoGrid').dataSource.read();
$('#GridName').data('kendoGrid').refresh();
For a auto refresh feature have a look here
By using following code it automatically called grid's read method and again fill grid
$('#GridName').data('kendoGrid').dataSource.read();
An alternative way to reload the grid is
$("#GridName").getKendoGrid().dataSource.read();
You can always use $('#GridName').data('kendoGrid').dataSource.read();. You don't really need to .refresh(); after that, .dataSource.read(); will do the trick.
Now if you want to refresh your grid in a more angular way, you can do:
<div kendo-grid="vm.grid" id="grid" options="vm.gridOptions"></div>
vm.grid.dataSource.read();`
OR
vm.gridOptions.dataSource.read();
And don't forget to declare your datasource as kendo.data.DataSource type
I want to go back to page 1 when I refresh the grid. Just calling the read() function will keep you on the current page, even if the new results don't have that many pages. Calling .page(1) on the datasource will refresh the datasource AND return to page 1 but fails on grids that aren't pageable. This function handles both:
function refreshGrid(selector) {
var grid = $(selector);
if (grid.length === 0)
return;
grid = grid.data('kendoGrid');
if (grid.getOptions().pageable) {
grid.dataSource.page(1);
}
else {
grid.dataSource.read();
}
}
In order to do a complete refresh, where the grid will be re-rendered alongwith new read request, you can do the following:
Grid.setOptions({
property: true/false
});
Where property can be any property e.g. sortable
You may try:
$('#GridName').data('kendoGrid').dataSource.read();
$('#GridName').data('kendoGrid').refresh();
Just write below code
$('.k-i-refresh').click();
$("#theidofthegrid").data("kendoGrid").dataSource.data([ ]);
If you are desiring the grid to be automatically refreshed on a timed basis, you can use the following example which has the interval set at 30 seconds:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
setInterval(function () {
var grid = $("#GridName").data("kendoGrid");
grid.dataSource.read();
}, 30000);
});
</script>
You can also refresh your grid with sending new parameters to Read action and setting pages to what you like :
var ds = $("#gridName").data("kendoGrid").dataSource;
ds.options.page = 1;
var parameters = {
id: 1
name: 'test'
}
ds.read(parameters);
In this example read action of the grid is being called by 2 parameters value and after getting result the paging of the grid is in page 1.
The default/updated configuration/data of the widgets is set to automatically bind to an associated DataSource.
$('#GridId').data('kendoGrid').dataSource.read();
$('#GridId').data('kendoGrid').refresh();
The easiest way out to refresh is using the refresh() function.
Which goes like:
$('#gridName').data('kendoGrid').refresh();
while you can also refresh the data source using this command:
$('#gridName').data('kendoGrid').dataSource.read();
The latter actually reloads the data source of the grid. The use of both can be done according to your need and requirement.
I see that a lot of answers here suggest calling both dataSource.read and grid.refresh, however, internally the grid listens for dataSource changes and upon a change it will refresh itself. In other words executing both dataSource.read and grid.refresh will result in refreshing the grid twice, which is unnecessary. Calling just dataSource.read is enough.
common js function for refresh kendo grid
function refreshKendoGrid(id) {
var grid = $("#" + id).data("kendoGrid");
if (grid) {
grid.dataSource.read();
}
}
My solution is:
var gridObj = $('#GridName').data('kendoGrid');
gridObj.dataSource.read();
gridObj.refresh();
Works also for other object functions
$("#grd").data("kendoGrid").dataSource.read();
$('#GridName').data('kendoGrid').dataSource.read(); //first you have to read the datasource data
$('#GridName').data('kendoGrid').refresh(); // after that you can refresh

Resources