Get a reference to Kendo Grid from inside the error handler

Viewed 15044

There already are questions how to get custom error handling, with answers, but all those answers use 'external' reference/selector to the grid to make it work, for example:

function onError(e) {
    if (e.errors) {
        var message = "Error:\n";  

        var grid = $('#gridID').data('kendoGrid'); // <<- here
    (...)
}

Is it possible to get the reference to the grid from inside the error handling function without providing the selector by hand or 'externally' (because global variables are meh)? That way the error handling script could be totally self-contained.

5 Answers

I know this is old, but it seems out of date. I needed to access the grid's name within the error because the error was coming from an 'inner grid' (from a template in and within the main grid's detail template). This is from the Telerik forums so I don't want to take credit for it, but it took me a bit to find it so I'm sharing here. For razor helpers,

@Html.Kendo().Grid<Model>()
   .DataSource(dataSource => dataSource
    .Events(events => events.Error("function(e){error_handler(e, 'GridName')"}))

For Jquery:

$("#Promotions").kendoGrid({
    dataSource: {
        error: errorHandler("#Promotions")
    }
});

and the Javascript function

Function error_handler(e, GridName)
{
}

you can use the overloaded method of Error() event and pass the grid name as a parameter like:

...
.Events(events => events.Error("function(e){error_handler(e, '#grid')}"))

javascript method:

function error_handler(e, gridName) {

    $(gridName).data("kendoGrid").cancelChanges();

    if (e.errors) {
        var message = "Errors:\n";
        $.each(e.errors, function (key, value) {

            if ('errors' in value) {
                $.each(value.errors, function () {
                    message += this + "\n";
                });
            }
        });

        alert(message);
    }        
}
Related