Attaching to Telerik MVC Grid’s client event using jQuery

Telerik MVC Grid component offers a way to subscribe to client side events by using ClientEvents method in your views. You can see the examples here: http://demos.telerik.com/aspnet-mvc/grid/events. It works fine, but sometimes you’d like to use jQuery to subscribe to these events more dynamically. An example of that might be a global error handler for all grids.

Although I couldn’t find a snippet on the web that does it, it turned out to be very easy. Just use the standard bind() method that jQuery offers, something like this:

$(function () {
    $('.t-grid').bind('error', function(e) {
        if (e.textStatus == 'error') {
            alert(e.XMLHttpRequest.responseText);
            e.preventDefault();
        }
    });
})

This event handler will show an error message if something went wrong during grid’s ajax call. Since this piece of code runs whenever the page loads it attaches to every grid (Telerik MVC Grids have t-grid CSS class applied) on the page. That way, we can change the behavior of the components more flexibly. As for the exact event names, it seems they’re the same as the methods you use in views, just without ‘On’ and starting lowercase, like ‘OnError’ -> ‘error’.

Advertisements

One thought on “Attaching to Telerik MVC Grid’s client event using jQuery

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s