Thursday, October 1, 2015

Kendo MVC Grid: generic approach for the error handling

Question: I am using the following code for the error handling for the MVC Grid control, I am wondering if there is generic way to get the grid object without using hardcoded grid name "#myGrid"? I am trying to write generic code for all razor views which are using the grid controls.

function error(args) {
            var grid = $("#myGrid").data("kendoGrid");
            if (grid.editable == undefined) {
                if (args.errors) {
                    for (var error in args.errors) {
                        App.error(args.errors[error].errors);
                    }
                }
                grid.cancelChanges();
            }
            else {
                grid.one("dataBinding", function (e) {
                    e.preventDefault();   // cancel grid rebind if error occurs

                    for (var error in args.errors) {
                        showMessage(grid.editable.element, error, args.errors[error].errors);
                    }
                });
            }
        }
Solution #1: 

crude way but working, just using selectors to grab all k-grid elements which return not-null for .data("kendoGrid") and compare the data sources with arg.sender. When the data sources match - we have a grid which raised the error:
$(".k-grid").each(function() {
    var grid = $(this).data("kendoGrid");
    if (grid !== null && grid.dataSource == args.sender) {
        // We have a winner!
    }
});
Solution #2: 
A possible solution would be to attach the error event handler like this:
.Events(e => e.Error(@
     function(e) {
         onError(e, "gridName");
     }
))
where onError is the error handler. This way you could add an additional parameter, which is the Grid name and access it in a generic way in the handler itself.
function onError(e, gridName) {
    ...
}

No comments: