Telerik Extensions for ASP.NET MVC

This help topic discusses the client-side API and events exposed by Telerik Grid for ASP.NET MVC.

Important

All Telerik UI components need a ScriptRegistrar component in order to output their JavaScript objects and register their JavaScript files. The ScriptRegistrar component should be defined *after* all other UI components in the page. If you create the components on the client-side and do not use the MVC extensions, you need to manually register all requried JavaScript files. For further information check this help topic (Step 4 - Register Scripts)

How to get the grid client-side object?

The grid client object is preserved in the data store for the grid element.

The following code snippet shows how to get the client object of the grid component.

CopyView
<%= Html.Telerik().Grid(Model)
        .Name("Grid")
%>
CopyJavaScript
<script type="text/javascript">
    // #Grid is a jQuery selector based on the "id" attribute of the grid. The id is set using Name()
    var grid = $("#Grid").data("tGrid");

    // use the grid object - call its ajaxRequest method
    grid.ajaxRequest();

</script>

Client events

Telerik Grid for ASP.NET MVC exposes the following client-side events

  • OnLoad - raised when the grid is initialized.
  • OnColumnReorder - raised when the user reorders a grid column.
  • OnColumnResize - raised when the user resizes a grid column.
  • OnCommand - raised when the user trigger a built-in or custom command.
  • OnComplete - raised when an ajax request is complete. This includes responses from data binding or commands.
  • OnDetailViewCollapse - raised when the user collapses a detail view.
  • OnDetailViewExpand - raised when the user expands a detail view.
  • OnDelete - raised when the user deletes a grid row.
  • OnDataBinding - raised when the grid is binding (ajax or web-service).
  • OnDataBound - raised when the grid is bound (ajax or web-service).
  • OnEdit - raised when the user edits or inserts a row.
  • OnError - raised when an error occurs during databinding.
  • OnRowDataBound - raised when a row of the grid is databound.
  • OnRowSelect - raised when the user selects a row.
  • OnSave - raised when the user saves a row.
  • OnSubmitChanges - raised when the user clickes the "Save changes" button and cell edit mode is enabled.

OnLoad

The OnLoad event is raised when the grid is initialized. Here is a short example showing how to handle that event:
CopySubscribing to the OnLoad event
<%= Html.Telerik().Grid(Model)
        .Name("Grid")
        .ClientEvents(events => events.OnLoad("Grid_onLoad"))
%>
CopyHandling the OnLoad event
<script type="text/javascript">
function Grid_onLoad(e) {
    //`this` is the DOM element of the grid
    var grid = $(this).data("tGrid");

    //event handling code
}
</script>

OnColumnReorder

The OnColumnReorder event is raised when the user reorders a grid column. The event argument exposes three fields:
  • column - the column of the grid which is reordered
  • oldIndex - the old index (position) of the column
  • oldIndex - the new index (position) of the column
Here is a short example showing how to handle that event:
CopySubscribing to the OnColumnReorder event
<%= Html.Telerik().Grid(Model)
        .Name("Grid")
        .ClientEvents(events => events.OnColumnReorder("Grid_onColumnReorder"))
%>
CopyHandling the OnColumnReorder event
<script type="text/javascript">
function Grid_onColumnReorder(e) {
    var column = e.column;
    var newIndex = e.newIndex;
    var oldIndex = e.oldIndex;
    //event handling code
}
</script>

OnColumnResize

The OnColumnResize event is raised when the user resizes a grid column. The event argument exposes three fields:
  • column - the column of the grid which is resized
  • oldWidth - the initial width of the column
  • newWidth - the final width of the column
Here is a short example showing how to handle that event:
CopySubscribing to the OnColumnResize event
<%= Html.Telerik().Grid(Model)
        .Name("Grid")
        .ClientEvents(events => events.OnColumnResize("Grid_onColumnResize"))
%>
CopyHandling the OnColumnResize event
<script type="text/javascript">
function Grid_onColumnResize(e) {
    var column = e.column;
    var newWidth = e.newWidth;
    var oldWidth = e.oldWidth;
    //event handling code
}
</script>

OnCommand

The OnCommand event is raised when the user triggers a command (built-in or custom). The event argument exposes the following fields:
  • name - the name of the command which is executed. Built-in commands have the following names:
    CommandName
    Add new record"add"
    Edit"edit"
    Update"update"
    Insert"insert"
    Cancel"cancel"
    Delete"delete"
    Submit changes"submitChanges"
    Cancel changes"cancelChanges"
  • row - the <tr> DOM element of grid row which contains the command button (not avaiable for toolbar commands).
  • dataItem - the data item to which the current row is bound to (not avaialble for toolbar commands).
  • data - any additional data which is going to be sent to the server side.
Here is a short example showing how to handle that event:
CopySubscribing to the OnCommand event
<%= Html.Telerik().Grid(Model)
        .Name("Grid")
        .Columns(columns =>
        {
            columns.Command(commands => commands.Custom("viewDetails")
                .Text("View details")
                .Ajax(true)
                .Action("Index", "Home")
            );
        })
        .ClientEvents(events => events.OnCommand("Grid_onCommand"))
%>
CopyHandling the OnCommand event
<script type="text/javascript">
function Grid_onCommand(e) {
    if (e.name == "viewDetails") {
        // pass additional data to the action method using e.data and e.dataItem
        e.data = $.extend(e.data, {
            orderID: e.dataItem.OrderID;
        });
    }
}
</script>
Important
The OnCommand event is triggered only for Ajax enabled custom commands.

OnComplete

The OnComplete event is raised when the response from an ajax request is received. The grid makes ajax requests during data binding and command execution. The event argument exposes the following fields:
  • name - the name of the command which was completed. See the OnCommand event for a list of default command names. During databinding the name would be set to "dataBinding". For custom commands the name of the command would be used.
  • response - a JavaScript object containing the server response from the command or data binding operation (custom commands should return JSON).
Here is a short example showing how to handle that event:
CopySubscribing to the OnComplete event
<%= Html.Telerik().Grid(Model)
        .Name("Grid")
        .Columns(columns =>
        {
            columns.Command(commands => commands.Custom("viewDetails")
                .Text("View details")
                .Ajax(true)
                .Action("Index", "Home")
            );
        })
        .ClientEvents(events => events.OnComplete("Grid_onComplete"))
%>
CopyHandling the OnComplete event
<script type="text/javascript">
function Grid_onComplete(e) {
    if (e.name == "viewDetails") {
        var result = e.response;
        // use the response returned from the server
    }
}
</script>

OnDetailViewCollapse

The OnDetailViewCollapse event is raised when the user collapses a detail view. The event argument exposes two fields:
  • masterRow - the <tr> DOM element representing the master row
  • detailRow - the <tr> DOM element representing the detail row
Here is a short example showing how to handle that event:
CopySubscribing to the OnDetailViewCollapse event
<%= Html.Telerik().Grid(Model)
        .Name("Grid")
        .ClientEvents(events => events.OnDetailViewCollapse("Grid_onDetailViewCollapse"))
%>
CopyHandling the OnDetailViewCollapse event
<script type="text/javascript">
function Grid_onDetailViewCollapse(e) {
    var masterRow = e.masterRow;
    var detailRow = e.detailRow;
    //event handling code
}
</script>

OnDetailViewExpand

The OnDetailViewExpand event is raised when the user expands a detail view. The event argument exposes two fields:
  • masterRow - the <tr> DOM element representing the master row
  • detailRow - the <tr> DOM element representing the detail row
Here is a short example showing how to handle that event:
CopySubscribing to the OnDetailViewExpand event
<%= Html.Telerik().Grid(Model)
        .Name("Grid")
        .ClientEvents(events => events.OnDetailViewExpand("Grid_onDetailViewExpand"))
%>
CopyHandling the OnDetailViewExpand event
<script type="text/javascript">
function Grid_onDetailViewExpand(e) {
    var masterRow = e.masterRow;
    var detailRow = e.detailRow;
    //event handling code
}
</script>

OnDelete

The OnDelete event is raised when the user deletes a grid row. The event argument exposes one field:
  • dataItem - the JavaScript object to which the deleted row is bound to.
Here is a short example showing how to handle that event:
CopySubscribing to the OnDelete event
<%= Html.Telerik().Grid(Model)
        .Name("Grid")
        .ClientEvents(events => events.OnDelete("Grid_onDelete"))
%>
CopyHandling the OnDelete event
<script type="text/javascript">
function Grid_onDelete(e) {
    var dataItem = e.dataItem;
    //event handling code
}
</script>
You can modify the values event argument field in order to send additional values to the action method which will handle the operation. Here is an example
CopySending additional values to the server using the OnDelete event
<script type="text/javascript">
function Grid_onDelete(e) {
    // Send additional values
    e.values.Company = "Telerik";
}
</script>
Important
You can cancel the OnDelete event by calling the preventDefault method of the event argument:
CopyCancelling the OnDelete event
<script type="text/javascript">
function Grid_onDelete(e) {
    e.preventDefault();
}
</script>
Cancelling the OnDelete event will prevent the row from being deleted.

OnDataBinding

The OnDataBinding event is raised every time the grid is being databound on the client-side (during Ajax and WebService binding). The grid needs data binding on initial load, when the user changes the current page, sorts or applies filtering. Here is a short example showing how to handle that event:
CopySubscribing to the OnDataBindingEvent event
<%= Html.Telerik().Grid(Model)
        .Name("Grid")
        .ClientEvents(events => events.OnDataBinding("Grid_onDataBinding"))
%>
CopyHandling the OnDataBinding event
<script type="text/javascript">
function Grid_onDataBinding(e){
    //handling code
}
</script>
You can send additional data to the action method which provides data for the grid by handling the OnDataBinding event.
CopyProviding Additional Data via the OnDataBinding Event - View
<script type="text/javascript">
function Grid_onDataBinding(e) {
    var categoryValue = "Beverages";
    var priceValue = 3.14;

    // pass additional values by setting the "data" field of the event argument
    e.data = {
        // the key ("category") specifies the variable name of the action method which will contain the specified value
        category: categoryValue,
        price: priceValue
    };
}
</script>
CopyProviding Additional Data via the OnDataBinding Event - Controller
[GridAction]
public ActionResult Select(string category, double price)
{
    // use "category" and "price" to determine what data should be returned
    var products = Db.Products.Where(p => p.Category == category && p.Price == price);

    return View(new GridModel(products))
}
Important
You can cancel the OnDataBinding event by calling the preventDefault method of the event argument:
CopyCancelling the OnDataBinding event
<script type="text/javascript">
function Grid_onDataBinding(e) {
    e.preventDefault();
}
</script>
Cancelling the OnDataBinding event will prevent the grid from binding. No Ajax request will be made and the grid will remain empty.

OnDataBound

The OnDataBound event is raised when the grid is databound on the client side. Here is a short example showing how to handle that event:
CopySubscribing to the OnDataBound event
<%= Html.Telerik().Grid(Model)
        .Name("Grid")
        .ClientEvents(events => events.OnDataBound("Grid_onDataBound"))
%>
CopyHandling the OnDataBound event
<script type="text/javascript">
function Grid_onDataBound(e){
    //handling code
}
</script>

OnEdit

The OnEdit event is raised when the user inserts or edits a grid row. The event argument exposes three fields:
  • dataItem - the JavaScript object to which the editor row is bound to. It is undefined during insertion.
  • mode - a string whose value is either "insert" or "edit"
  • form - the <form> DOM element which contains all editing components (textboxes, checkboxes, dropdownlists etc.)
  • cell - the <td> DOM element which goes in edit mode. This field is available only in cell edit mode.
Here is a short example showing how to handle that event:
CopySubscribing to the OnEdit event
<%= Html.Telerik().Grid(Model)
        .Name("Grid")
        .ClientEvents(events => events.OnEdit("Grid_onEdit"))
%>
CopyHandling the OnEdit event
<script type="text/javascript">
function Grid_onEdit(e) {
    var dataItem = e.dataItem;
    var mode = e.mode;
    var form = e.form;
    //event handling code
}
</script>
The OnEdit event is suitable for custom initialization of the editing UI. This is done by using the dataItem and form fields of the event argument.
CopyInitializing editing controls in OnEdit
<script type="text/javascript">
function Grid_onEdit(e) {
    var dataItem = e.dataItem;
    var mode = e.mode;
    var form = e.form;
    var priceTextBox = $(form).find("#Price");

    if (mode == "insert") {
        // Set default value
        priceTextBox.val("Enter price");
    }

    var customerDropDownList = $(form).find("#Customer");
    if (mode == "edit") {
        //Select the proper dropdown list item
        customerDropDownList.val(dataItem.CustomerID);
    }

}
</script>

OnError

The OnError event is raised when there is an error during databiding. The event argument exposes three fields:
  • XMLHttpRequest - the current XMLHttpRequest object
  • textStatus - a text field which can have one of the following values:
    • error - the server returned HTTP code 500 (server error) or 404 (not found). The first can occur if there is an unhandled exception in the action method which has been requested (the one specified via the grid databinding settings). The latter will occur if the requested URL does not exist (the controller or action specified in the grid binding settings are invalid).
    • timeout - the server did not respond within in time
    • parsererror - the server returned unexpected response. The grid expects JSON response to be returned and any other content will trigger the OnError event. This may occur if you forget to use the [GridAction] attribute or the GridModel class when implementing the action method which binds the grid.
    • modelstateerror - there were model state errors during the previous update, delete or insert operation.
  • modelState - available only when textStatus is equal to "modelstateerror". Contains a key / value pairs where the key is the model property name and the value is an object containing the model state data (errors etc.):
    CopyModel State
    <script type="text/javascript">
    function Grid_onError(e) {
        if (e.textStatus == "modelstateerror") {
            console.log(e.modelState);
            // displays something like {"ProductName":{"errors":["The Product name field is required."]}}
            }
    }
    </script>
Here is a short example showing how to handle that event:
CopySubscribing to the OnError event
<%= Html.Telerik().Grid(Model)
        .Name("Grid")
        .ClientEvents(events => events.OnError("Grid_onError"))
%>
CopyHandling the OnError event
<script type="text/javascript">
function Grid_onError(e) {
    //`this` is the DOM element of the grid
    var grid = $(this).data("tGrid");

    //the current XMLHttpRequest object
    var xhr = e.XMLHttpRequest;
    //the text status of the error - "timeout", "error" etc.
    var status = e.textStatus;

    if (status == "error") {
        //xhr.status is the HTTP code returned by the server
        if (xhr.status == "404") {
            alert("requested url not found")
        }
    }
}
</script>
The following example shows how to display any model state errors (custom or caused by model validation):
CopyShowing Model State Errors
<script type="text/javascript">
function Grid_onError(args) {
    // check if there are any model state errors
    if (args.textStatus == "modelstateerror" && args.modelState) {
        // accumulate the error messages in the "message" variable
        var message = "Errors:\n";

        // iterate over each key value pair
        $.each(args.modelState, function (key, value) {
            if (value.errors) {
            // iterate over all errors and accumulate them in the "message" variable
                $.each(value.errors, function(index, error) {
                    message += error + "\n";
                });
            }
        });
        args.preventDefault();
        alert(message);
   }
}
</script>
Important
You can cancel the OnError event by calling the preventDefault method of the event argument:
CopyCancelling the OnError event
<script type="text/javascript">
function Grid_onError(e) {
    e.preventDefault();
}
</script>
Cancelling the OnError event will prevent the grid from showing a message box with error details.

OnRowDataBound

The OnRowDataBound event is raised during client binding. The event argument exposes two fields:
  • row - the DOM element <tr> of the bound row
  • dataItem - the JavaScript object to which the row is being bound to
Here is a short example showing how to handle that event:
CopySubscribing to the OnRowDataBound event
<%= Html.Telerik().Grid(Model)
        .Name("Grid")
        .ClientEvents(events => events.OnRowDataBound("Grid_onRowDataBound"))
%>
CopyHandling the OnRowDataBound event
<script type="text/javascript">
function Grid_onRowDataBound(e) {
    //the DOM element (<tr>) representing the row which is being databound
    var row = e.row;
    //the data item - JavaScript object.
    var dataItem = e.dataItem;

    //You can use the OnRowDataBound event to customize the way data is presented on the client-side

    row.cells[1].innerHTML = "<strong>" + dataItem.text + "</strong>";
}
</script>
You can use the OnDataBound event to subscribe to DOM events of HTML elements which are defined as part of a column template:
CopySubscribing to events in client templates - declaration
<%= Html.Telerik().Grid<MyApplication.Models.Product>()
        .Name("Grid")
        .Columns(columns =>
        {
            columns.Bound(p => p.ProductID);
            columns.Bound(p => p.ProductName);
            columns.Bound(p => p.ProductID).ClientTemplate("<a href="#" class="t-button">View Details</a>");
        })
        .DataBinding(dataBinding => dataBinding.Ajax().Select("Action", "Controller"))
        .ClientEvents(e => e.OnRowDataBound("Grid_onRowDataBound"))
%>
CopySubscribing to events in client templates - event handler
<script type="text/javascript">
function Grid_onRowDataBound(e) {
    var dataItem = e.dataItem;
    var productID = dataItem.ProductID;

    $(e.row).find("a.t-button")// find the link defined in the template column
        .click(function(e) { // subscribe to its click event
            //handle the click event e.g. navigate to a detail page passing the current ProductID

            location.href = "/Controller/Details/" + productID;
        });
}
</script>

OnRowSelect

The OnRowSelect event is raised when the user selects a grid row. The event argument exposes one field:
  • row - the <tr> DOM element of selected grid row
Here is a short example showing how to handle that event:
CopySubscribing to the OnRowSelect event
<%= Html.Telerik().Grid(Model)
        .Name("Grid")
        .ClientEvents(events => events.OnRowSelect("Grid_onRowSelect"))
%>
CopyHandling the OnRowSelect event
<script type="text/javascript">
function Grid_onRowSelect(e) {
    var row = e.row;
    //event handling code

}
</script>
A common requirement is to use the data item to which the selected row is bound. Here is how to do so:
CopyGetting the data item to which the selected row is bound to
<script type="text/javascript">
function Grid_onRowSelect(e) {
    // get the DOM element which represents the clicked row
    var row = e.row;
    // get the instance of the grid client-side object
    var grid = $(this).data("tGrid");
    // use the dataItem method of the grid to get the data item to which the row is bound to
    var dataItem = grid.dataItem(row);

    // use the obtained data item for something e.g. navigate to a new page passing some property as an argument
    location.href = "/Home/ShowDetails/" + dataItem.ProductID;
}
</script>

OnSave

The OnSave event is raised when the user inserts or edits a grid row. The event argument exposes three fields:
  • dataItem - the item from the data source (data item) to which the grid row is bound to.
  • values - the values entered by the user
  • form - the <form> DOM element which contains the editing form elements.
  • cell - the <td> DOM element which is in edit mode. This field is available only in cell edit mode.
Here is a short example showing how to handle that event:
CopySubscribing to the OnSave event
<%= Html.Telerik().Grid(Model)
        .Name("Grid")
        .ClientEvents(events => events.OnSave("Grid_onSave"))
%>
CopyHandling the OnSave event
<script type="text/javascript">
function Grid_onSave(e) {
    var dataItem = e.dataItem;
    var values = e.values;
    var form = e.form;
    //event handling code
}
</script>
You can modify the values event argument field in order to modify the values entered by the user or to send additional values to the action method which will handle the operation. Any updated values will override what the user has entered. Here is an example
CopySending additional values to the server using the OnSave event
<script type="text/javascript">
function Grid_onSave(e) {
    var values = e.values;
    // Update existing value
    if (values.ContactName == "") {
        values.ContactName = "N/A";
    }
    // Send additional values
    values.Company = "Telerik";
}
</script>
Sending an array of complex objects however is not as straightforward as sending simple values. jQuery sends arrays of complex objects in a way which is not supported by the default ASP.NET MVC model binder. Here is an example showing how to send a JavaScript array of complex objects as additional value.
CopyModel declaration
public class Team
{
    public string TeamID { get; set; }
    public IEnumerable<TeamMember> TeamMembers { get; set; }
}

public class TeamMember
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
CopySending array of JavaScript objects as additonal value
<script type="text/javascript">
function Grid_onSave(e) {

    var teamMembers = [
        { FirstName: "John", LastName: "Doe" },
        { FirstName: "Jane", LastName: "Doe" }
    ];

    // send all properties of the object in the form key -> value
    // key is composed from the server property name (TeamMembers) and index ([0]) e.g. "TeamMembers[0].FirstName", "TeamMembers[0].LastName"

    for (var i = 0; i < teamMembers.length; i++) {
        var teamMember = teamMembers[i];
        // Send the FirstName
        e.values["TeamMembers[" + i + "].FirstName"] = teamMember.FirstName;
        // Send the LastName
        e.values["TeamMembers[" + i + "].LastName"] = teamMember.LastName;
    }
}
</script>
Important
You can cancel the OnSave event by calling the preventDefault method of the event argument:
CopyCancelling the OnSave event
<script type="text/javascript">
function Grid_onSave(e) {
    e.preventDefault();
}
</script>
Cancelling the OnSave event will prevent the grid from saving the data. No request will be made to the server.

OnSubmitChanges

The OnSubmitChanges event is raised when the user clickes the "Save changes" button and cell edit mode is enabled. The event argument exposes three fields:
  • inserted - an array of data items which have been inserted.
  • updated - an array of data items which have been updated.
  • deleted - an array of data items which have been updated.
Here is a short example showing how to handle that event:
CopySubscribing to the OnSubmitChanges event
<%= Html.Telerik().Grid(Model)
        .Name("Grid")
        .ClientEvents(events => events.OnSubmitChanges("Grid_onSubmitChanges"))
%>
CopyHandling the OnSubmitChanges event
<script type="text/javascript">
function Grid_onSubmitChanges(e) {
    var inserted = e.inserted;
    var updated = e.updated;
    var deleted = e.deleted;
    //event handling code
}
</script>
CopySending additional data to the server
<script type="text/javascript">
function Grid_onSubmitChanges(e) {
    e.values.Company = "Telerik";                                            
}
</script>
Important
You can cancel the OnSubmitChanges event by calling the preventDefault method of the event argument:
CopyCancelling the OnSubmitChanges event
<script type="text/javascript">
function Grid_onSubmitChanges(e) {
    e.preventDefault();
}
</script>
Cancelling the OnSubmitChanges event will prevent the grid from submiting the changes. No request will be made to the server.

Client Properties

Telerik Grid for ASP.NET MVC exposes the following client-side properties:

currentPage

Returns the current page of the grid. The initial value is 1.

data

Returns an array of data items which represent the currently displayed data. Contains only one page of the data if paging is enabled. Not available in server binding scenarios.

filterBy

Returns the current filter expression of the grid. The initial value is "" (empty string). Check the filter JavaScript method for additional reference.

orderBy

Returns the current sort expression of the grid. The initial value is "" (empty string). Check the sort JavaScript method for additional reference.

total

Returns the total number of items in the data source.

Client Methods

Telerik Grid for ASP.NET MVC exposes the following client-side methods:
  • Row methods:
    • addRow - adds a new empty row in edit mode.
    • collapseRow - hides the detail view of the specified master table row.
    • deleteRow - deletes the specified row by sending a request to the server.
    • editRow - puts the specified table row in edit mode.
    • expandRow - shows the detail view of the specified master table row.
    • insertRow - inserts the specified row or an object by sending a request to the server.
    • updateRow - updates the specified row or an object by sending a request to the server.
  • Methods for InCell editing mode:
    • cancelChanges - cancels any pending changes during InCell editing mode.
    • hasChanges - returns true if the user has modified the grid cell during InCell editing mode.
    • submitChanges - submits any pending changes during InCell editing mode.
    • cancelCell - cancels the changes made to the cell and exits edit mode.
    • editCell - puts a cell into edit mode.
    • saveCell - saves the changes made to the cell and exits edit mode.
  • Grouping methods:
  • Methods used to get the modifications made during InCell editing
  • ajaxRequest - initiates an ajax request to populate the grid with data. Used to refresh the grid.
  • dataBind - binds the grid to the specified array of objects.
  • dataItem - gets the data item to which the specified grid row (TR DOM element) is bound to.
  • filter - filters the grid using the specified filter expression.
  • hideColumn - hides a Grid column.
  • pageTo - changes the current page and rebinds the grid.
  • rebind - rebinds the grid. The current grid state (page, sort order etc.) is lost.
  • serializeData - serializes an array of objects so the result can be send to an action method.
  • showColumn - shows a Grid column.
  • sort - sorts the grid using the specified sort expression.

addRow

The addRow method adds a new empty table row in edit mode.
CopyaddRow example
var grid = $("#Grid").data("tGrid");

grid.addRow();
Note
The addRow method triggers the OnEdit event. The "mode" field of the OnEdit event argument is set to "insert".
Important
The addRow does not save the newly created table row. Use the insertRow to save the row.

ajaxRequest

The ajaxRequest method initiates an ajax request for a client-side bound grid which will rebind the grid using the current grid state (current page, sort order etc.)
CopyajaxRequest example
var grid = $("#Grid").data("tGrid");

grid.ajaxRequest();
Note
The ajaxRequest method triggers the OnDataBinding event.

cancelCell

The cancelCell method cancels the changes made to the passed td DOM element and exits edit mode.
CopycancelCell example
var grid = $("#Grid").data("tGrid");

grid.cancelCell('#Grid td:first');//cancels the cell in the first row/column
Note
The cancelCell method do not trigger the OnSave event.
Important
The cancelCell method works only during InCell editing mode.

editCell

The editCell method puts a td DOM element into edit mode.
CopyeditCell example
var grid = $("#Grid").data("tGrid");

grid.editCell('#Grid td:first');
Note
The editCell method triggers the OnEdit event.
Important
The editCell method works only during InCell editing mode.

saveCell

The saveCell method saves the changes made to the passed td DOM element and exits edit mode.
CopysaveCell example
var grid = $("#Grid").data("tGrid");

grid.saveCell('#Grid td:first');//cancels the cell in the first row/column
Note
The saveCell method triggers the OnSave event.
Important
The saveCell method works only during InCell editing mode.

cancelChanges

The cancelChanges method cancels any pending changes during InCell editing mode. Deleted rows are restored. Inserted rows are removed. Updated rows are restored to their original values.
CopycancelChanges example
var grid = $("#Grid").data("tGrid");

grid.cancelChanges();
Important
The cancelChanges method works only during InCell editing mode.

collapseGroup

The collapseGroup method collapses the specified group table row.
CopycollapseGroup example
var grid = $("#Grid").data("tGrid");
// get the first master table row
var tr = $("#Grid tbody > .t-grouping-row:eq(0)"); // use .t-grouping-row to select only the master rows

// collapse the group row
grid.collapseGroup(tr);

collapseRow

The collapseRow method hides the detail view of the specified master row.
CopycollapseRow example
var grid = $("#Grid").data("tGrid");
// get the first master table row
var tr = $("#Grid tbody > .t-master-row:eq(0)"); // use .t-master-row to select only the master rows

// collapse the row
grid.collapseRow(tr);

dataBind

The dataBind method binds the grid to the specified array of JavaScript objects. The columns of the grid need to be configured to match the properties of the JavaScript objects passed as datasource.
CopydataBind example
var grid = $("#Grid").data("tGrid");
var data = new [
    {OrderID: 1, ShipAddress: "Address #1"},
    {OrderID: 2, ShipAddress: "Address #2"},
]

grid.dataBind(data);

dataItem

The dataItem method returns the data item to which a given table row (tr DOM element) is bound. You can supply a DOM element, jQuery object or a string selector as an argument.
CopydataItem example
var grid = $("#Grid").data("tGrid");
// get the first table row
var tr = $("#Grid tbody tr:eq(1)"); // use eq(1) if the grid is scrollable or eq(0) if not to get the first row
// get the associated data item
var dataItem = grid.dataItem(tr);

deleteRow

The deleteRow method deletes the specified row by sending a request to server. The Delete setting from the grid data binding configuration is used. It requires a jQuery object representing the table row.
CopydeleteRow example
var grid = $("#Grid").data("tGrid");
// get the first table row
var tr = $("#Grid tbody tr:eq(1)"); // use eq(1) if the grid is scrollable or eq(0) if not to get the first row
// delete the row
grid.deleteRow(tr);
Note
The deleteRow method triggers the OnDelete event.

editRow

The editRow method puts the specified table row in edit mode. It requires a jQuery object representing the table row:
CopyeditRow example
var grid = $("#Grid").data("tGrid");
// get the first table row
var tr = $("#Grid tbody tr:eq(1)"); // use eq(1) if the grid is scrollable or eq(0) if not to get the first row
// start editing
grid.editRow(tr);
Note
The editRow method triggers the OnEdit event. The "mode" field of the OnEdit event argument is set to "edit".

expandGroup

The expandGroup method expands the specified group table row.
CopycollapseGroup example
var grid = $("#Grid").data("tGrid");
// get the first master table row
var tr = $("#Grid tbody > .t-grouping-row:eq(0)"); // use .t-grouping-row to select only the master rows

// expand the group row
grid.expandGroup(tr);

expandRow

The expandRow method shows the detail view of the specified master row.
CopyexpandRow example
var grid = $("#Grid").data("tGrid");
// get the first master table row
var tr = $("#Grid tbody > .t-master-row:eq(0)"); // use .t-master-row to select only the master rows

// expand the row
grid.expandRow(tr);

filter

The filter method filters the contents of the grid based on the specified filter expression.
Copyfilter example
var grid = $("#Grid").data("tGrid");
//Display all records whose OrderID property is equal to 10248
grid.filter("OrderID~eq~10248");
Important
The filter JavaScript function is available only if filtering is enabled. If the Required JavaScript files are manually included make sure telerik.grid.filtering.js has been included.
Filter expressions are constructed in the following manner:

member~filterOperator~value or

filterFunction(member,value) where

  • member is the member (property of field) to which the column is bound to. Here are two examples:
    CopyComposite member
    <%= Html.Telerik().Grid(Model)
            .Columns(o => o.Customer.ContactName); //the member here is "Customer.ContactName"
    %>
    CopySimple member
    <%= Html.Telerik().Grid(Model)
            .Columns(o => o.OrderID); //the member here is "OrderID"
    %>
  • filterOperator is the comparison operator. The following comparison operators are supported:
    OperatorDescriptionExample
    eqIs equal toContactName~eq~'Paul Henriot'
    neIs not equal toOrderID~ne~10248
    gtIs greater thanOrderID~gt~10248
    geIs greater than or equal toOrderID~ge~10248
    ltIs less thanOrderID~lt~10248
    leIs less than or equal toOrderID~le~10248
    Important
    All filter operators are supported for numeric (integer, decimal, float, double) and date members. Only eq and ne are supported for string, enum and boolean members.
  • filterFunction is any of the filter functions:
    FunctionDescriptionExample
    endswithEnds withendswith(ContactName,'Henriot')
    startswithStarts withstartswith(ContactName,'Henriot')
    substringofContainssubstringof(ContactName,'Paul')
    Important
    Filter functions are supported only for string members.
To make a composition of filter expressions (when you want to filter by more than one member) use the and keyword. The following filter expression will show records for which the contact name starts with "Paul" and the order is is greater than 10248.

startswith(Customer.ContactName,'Paul')~and~OrderID~gt~10248

If you have more than two statements in your filter expression, you should declare them using parentheses.

grid.filter("(OrderID~eq~1~or~OrderID~eq~2)~or~(OrderID~eq~3~or~OrderID~eq~4)")

hasChanges

The hasChanges method checks if the user has modified the grid during InCell editing mode. Modifications include deleting a row, adding a row or changing a row. Returns true if there are changes; otherwise false.
CopyhasChanges example
var grid = $("#Grid").data("tGrid");

var hasChanges  = grid.hasChanges();
Important
The hasChanges method works only during InCell editing mode.

hideColumn

The hideColumn method hides a currently visible column, specified by its index or column object.
CopyhideColumn example
var grid = $("#Grid").data("tGrid");

grid.hideColumn(0); // hide the first column

insertRow

The insertRow method inserts the specified row or an object by sending a request to server. The Insert setting from the grid data binding configuration is used. It requires a jQuery object representing the table row or an object representing the model.
CopyinsertRow row example
var grid = $("#Grid").data("tGrid");

var newRow = $("#Grid .t-grid-new-row"); // get the last added row

grid.insertRow(newRow);
CopyinsertRow object example
var grid = $("#Grid").data("tGrid");

var product = { ProductName: "KeyBoard", UnitPrice: 53.20};

grid.insertRow(product);
Note
When used with object in InCell editing mode the insertRow adds the object to the change log without performing an Ajax request.
Note
The insertRow method triggers the OnSave event. The "mode" field of the OnSave event argument is set to "insert".

insertedDataItems

Returns an array of data items which represent the inserted objects during InCell editing.
CopyinsertedDataItems example
var grid = $("#Grid").data("tGrid");                                        
var inserted = grid.insertedDataItems();

updatedDataItems

Returns an array of data items which represent the updated objects during InCell editing.

deletedDataItems

Returns an array of data items which represent the deleted objects during InCell editing.
Important
The insertedDataItems,updatedDataItems,deletedDataItems methods work only during InCell editing.

pageTo

The pageTo method sets the current page of the grid to the specified page number. The page number must be valid - within the range of available pages.
CopypageTo example
var grid = $("#Grid").data("tGrid");
//go to the 10th page
grid.pageTo(10);
Important
It is important to note that the pageTo method expects a page number (starting from 1) not page index (starting from 0). Thus to navigate to the first page you need to call grid.pageTo(1).

rebind

The rebind method rebinds a client-side bound grid. You can pass additional arguments to the action method or web service method using rebind .
Copyrebind example
var grid = $("#Grid").data("tGrid");
//send additional arguments by passing them as a literal JavaScript object
grid.rebind({customerID : "ALFKI"});
Note
The difference between ajaxRequest and rebind is that rebind resets the state of the grid - current page, sorted columns and applied filters.

serializeData

The serializeData method serializes an array of JavaScript objects in a format ready to be send to an action method after parsed to JSON. The method accepts an array, a prefix and an optional predicate, which can be used to filter the data for serialization.
CopyserializeData example
var data =[
    {
        ProductName: "Keyboard", 
        UnitPrice: 55.23
    },
    {
        ProductName: "Printer", 
        UnitPrice: 102.1
    }];

var result = grid.serializeData(data,"updated");
CopyserializeData with predicate
var result = grid.serializeData(data,"updated",function (product){
    if(product.UnitPrice < 100){
          return true;
      }
});
When send to the server the serialized object can be retrieved with the used prefix.

showColumn

The showColumn method shows a currently hidden column, specified by its index or column object.
CopyhideColumn example
var grid = $("#Grid").data("tGrid");

grid.showColumn(0); // show the first column

sort

The sort method sorts the contents of the grid based on the specified sort expression.
Copysort example
var grid = $("#Grid").data("tGrid");
//Descendingly sort the records by the OrderID property
grid.sort("OrderID-desc");
Sort expressions are constructed in the following manner:

member-order where

  • member is the member (property of field) to which the column is bound to. Here are two examples:
    CopyComposite member
    <%= Html.Telerik().Grid(Model)
            .Columns(o => o.Customer.ContactName); //the member here is "Customer.ContactName"
    %>
    CopySimple member
    <%= Html.Telerik().Grid(Model)
            .Columns(o => o.OrderID); //the member here is "OrderID"
    %>
  • order is the sort order. The following sort orders are supported
    OrderDescriptionExample
    ascAscendingContactName-asc
    descDescendingOrderID-desc
To make a composition of sort expressions (when you want to sort by more than one member) use ~ keyword. The following sort expression will sort by the Customer.ContactName and OrderID members:

Customer.ContactName-asc~OrderID-desc

To remove the sorting you can use the empty sort expression - "":
Copyclear sort example
var grid = $("#Grid").data("tGrid");
//Remove all sorting
grid.sort("");

submitChanges

The submitChanges method submits any pending changes during InCell editing mode. The Update setting from the grid data binding configuration is used.
CopysubmitChanges example
var grid = $("#Grid").data("tGrid");

grid.submitChanges();
Important
The submitChanges method works only during InCell editing mode.

updateRow

The updateRow method updates the specified row or an object by sending a request to server. The Update setting from the grid data binding configuration is used. It requires a jQuery object representing the table row or an object representing the model.
CopyupdateRow row example
var grid = $("#Grid").data("tGrid");
var row = $("#Grid .t-grid-edit-row"); //get the current row which is in edit mode
grid.updateRow(row);
CopyupdateRow object example
var grid = $("#Grid").data("tGrid");

// the property declared as DataKey needs to be included in the object
var product = {ProductID: 1, ProductName: "KeyBoard", UnitPrice: 53.20};                                         

grid.updateRow(product);
Note
When used with object in InCell editing mode the updateRow adds the object to the change log without performing an Ajax request.
Note
The updateRow method triggers the OnSave event. The "mode" field of the OnSave event arguments is set to "edit".

Binding to external WebService

The following example shows how to use the client-side API and events in order to bind the grid to external web service.
CopyView
<%= Html.Telerik().Grid<TwitterItem>()
        .Name("Grid")
        .Columns(columns =>
        {
            //Empty column
            columns.Bound(o => { }).Title("Author").Width(100);
            //Empty column
            columns.Bound(o => { }).Title("Avatar").Width(80);
            //Bound column
            columns.Bound(o => o.text).Title("Post");
        })
        .ClientEvents(events => events
            .OnDataBinding("onDataBinding")
            .OnRowDataBound("onRowDataBound"))
        .Scrollable(scrolling=>scrolling.Height(400))
    %>
CopyImplementation
function onRowDataBound(e) {
    var row = e.row;
    var dataItem = e.dataItem;

    // update `Author` cell with template
    row.cells[0].innerHTML = [
    "<a class="t-link" href="http://www.twitter.com/", dataItem.from_user, "">",
        dataItem.from_user,
        "</a>"
    ].join("");

    // update `Avatar` cell with template
    row.cells[1].innerHTML = [
    "<img width="48" height="48"",
        " src="", dataItem.profile_image_url,
        "" alt="", dataItem.from_user, "" />"
    ].join("");
}

function onDataBinding(e) {
    var grid = $(this).data("tGrid");

    // call the twitter search api
    $.ajax({
        url: "http://search.twitter.com/search.json",
        contentType: "application/json; charset=utf-8",
        type: "GET",
        dataType: "jsonp",
        error: function(xhr, status) {
            alert(status);
        },
        data: {
            q: $("#searchText").val()
        },
        success: function(result) {
            grid.dataBind(result.results);
        }
    });
}

See Also

Other Resources