Hi i am new in asp.net mvc and telerik controls. How can i get o.Id value when i click on row?
<%= Html.Telerik().Grid(Model)
.Name("RolesGrid")
.DataKeys(keys => keys.Add(o => o.Id))
.Selectable()
.Columns(columns =>
{
columns.Bound(o => o.Name);
columns.Bound(o => o.Description);
})
.Pageable()
.ClientEvents(events => events
.OnRowSelect("onRowSelect"))
%>
in js code:
function onRowSelect(e) {
var ordersGrid = $('#RolesGrid').data('tGrid');
var row = e.row;
var dataItem = ordersGrid.dataItem(row);
alert(dataItem);
}
But dataItem is null and there is no id开发者_Go百科 value in generated html file. Thanks and sorry for my bad english
So after all i have the best way to get id is:
- bind onRowSelect function to your grid
write next code in onRowSelect
var dataItem = jQuery('#MyGridId').data('tGrid').dataItem(e.row); alert(dataItem['Id']);
dataItem is a map witch have all properties of grid model so you get all you want
Thats all, thanks
From telerik grid demo.
You have to put the Id in the telerik grid as a hidden column.
// ...
.DataKeys(keys => keys.Add(o => o.Id))
.Selectable()
.Columns(columns =>
{
columns.Bound(o => o.Id).Hidden();
columns.Bound(o => o.Name);
columns.Bound(o => o.Description);
})
// ...
.ClientEvents(events => events.OnRowSelect("onRowSelect"))
It will render a
<td style="display: none; ...">...</td>
And then you get it like this:
function onRowSelect(e) {
var id = e.row.cells[0].innerHTML;
// ...
}
Notes:
- I know, it's ugly.
- I don't know why the telerik forces you to call the
.DataKeys(...)
method if there's no documented way to get the value for the key defined. - If you use grouping or some other feature it gets trickier, as the hidden column position varies depending on the grouping arrangement.
I found a slightly more elegant way to do this that borrows off of mmutilva's answer.
Start by putting in the hidden column and the change event in the same way:
.DataKeys(keys => keys.Add(o => o.Id))
.Selectable()
.Columns(columns =>
{
columns.Bound(o => o.Id).Hidden();
columns.Bound(o => o.Name);
columns.Bound(o => o.Description);
})
.ClientEvents(events => events.OnRowSelect("onRowSelect"))
But then in the javascript function, there is a better way to actually select the object and then the hidden row:
function onRowSelect(e) {
var grid = e.sender;
var currentitem = grid.dataItem(this.select());
var Id = currentitem.Id;
//then do whatever with the ID variable
}
Source
Change the function onRowSelect to this:
function onRowSelect(sender, args){...}
The sender will be the grid, and from the args you can determine which item was selected.
Look to the Telerik help site for detailed info on how to get the data using the Client Side API: http://www.telerik.com/help
精彩评论