
i am using radgrid for asp.net ajax.
this is my client side event on pageindexchanged,
function
Confirm(PageChange)
{
var
PageChangeValue=document.getElementById(PageChange).value;
if(PageChangeValue == 1)
{
if(confirm("WARNING: Any unsaved changes will be lost. Do you want to save your work? \n Press OK to stop and save (You must use the save button). \n Press Cancel to continue without saving.")== false)
{
document.getElementById(PageChange).value=0;
}
else
{
return false;
}
}
}
if the confirmation is ok then only it will go to next page.
but when i click on the next page, it fires the clientside script, opens the confirmation dialog box and didnt wait for the confirmation. automatically it goes to the next page.
both clientside and serverside pageindexchanged event fired simultanouesly.
before that in radgrid for asp.net control , this functionality works fine.
how to solve this issue.
thanks,
21 Answers, 1 is accepted
By default, RadGrid does not provide cancellation of paging on the client without posting back to the server. Even if you hook up to the OnCommand client-side event and set set_cancel(true), RadGrid will still postback, without changing the page. If this is OK with you, you can simply use:
function onCommand(sender, args) |
{ |
if(args.get_commandName() == "Page") |
{ |
args.set_cancel(confirm("Are you sure you want to page?")); |
} |
} |
This, however, will not prevent postback to the server. If you need to prevent any postback at all, the easiest approach to take is to find all your anchor and input elements in the pager row and assign additional click event handlers to them:
function gridCreated(sender, args) { |
var pagerRow = sender.get_masterTableView().get_element().tFoot; |
var anchors = pagerRow.getElementsByTagName('a'); |
for (var i = 0; i < anchors.length; i++) { |
if (anchors[i].className != "rgCurrentPage" && anchors[i].href.indexOf("javascript:__doPostBack") > -1) { |
var clickScript = anchors[i].attributes["onclick"].value; |
anchors[i].onclick = confirmPage; |
} |
} |
var submits = pagerRow.getElementsByTagName('input'); |
for (var i = 0; i < submits.length; i++) { |
if (submits[i].type == "submit") { |
submits[i].onclick = confirmPage; |
} |
} |
} |
function confirmPage() |
{ |
return confirm("Page?"); |
} |
The above code seems quite more complicated from the previous, but it assigns a confirmPage() handler to each and every button in the pager, so that you can cancel paging without raising any further events.
Greetings,
Veli
the Telerik team
Instantly find answers to your questions on the new Telerik Support Portal.
Check out the tips for optimizing your support resource searches.

i have the same need can you please provide a sample ?
When using server-side paging with RadGrid, the pager item renders two types of pager buttons. The Prev/Next and First/Last page buttons are submit buttons (<input type='submit'>), while the go-to-page buttons (the page numers) are link buttons (rendered as <a href="javascript:__doPostBack(...)">).
When we want to intercept a page command and prevent the grid from postbacking at all, we need to find all those pager buttons and modify their behavior. For link buttons, we need get the href attribute of the links and replace them with a wrapper method that will execute the script inside only after user confirmation.
For submit buttons, similarly, we need to attach a client click handler to each of them. The handler will return true/false depending on user confirmation and no postback will occur if the user cancels paging.
For your convenience, two sample pages are attached. The approach I have mentioned is demonstrated in both of them. One of them uses DOM traversal to iterate over all link and submit buttons, while the second examples is equivalent to the first, but uses jQuery instead. Check these out.
In the example with jQuery, I have used the jQuery version supplied in the Telerik.Web.UI assembly. You can use your own, or, similarly, use the one supplied with your Telerik.Web.UI assembly, as discussed in this blog post.
Best wishes,
Veli
the Telerik team
Watch a video on how to optimize your support resource searches and check out more tips on the blogs.
Follow the status of features or bugs in PITS and vote for them to affect their priority.


function
pageLoad(sender, args) {
var
$ = $telerik.$;
var
pagerCellSelector =
"#<%= rgContracts.ClientID %> td.rgPagerCell"
;
$(pagerCellSelector +
" a[href^='javascript:__doPostBack']"
).each(
function
() {
this
.href = String.format(
"javascript:confirmOnPage(\"{0}\")"
,
this
.href.replace(
"javascript:"
,
""
));
});
$(pagerCellSelector +
" input[type='button'][class^='rgPage']"
).each(
function
() {
this
.onclick =
function
() {
return
confirmOnPage(
""
);
}
});
}
function
confirmOnPage(originalScript) {
var
UnSavedChangesValue = document.getElementById(
'<%=hdUnSavedChanges.ClientID %>'
).value;
var
callBackFn =
function
(arg) {
if
(arg) {
document.getElementById(
'<%=hdUnSavedChanges.ClientID %>'
).value = 0;
eval(originalScript);
return
arg;
}
else
{
return
arg;
}
}
if
(UnSavedChangesValue == 1) {
radconfirm(
"<strong style='color:#00ff'>WARNING</strong>: Any unsaved changes will be <strong>lost</strong>. Do you still wish to change pages? To save your work first, click No, and then click the <strong>Save</strong> button."
, callBackFn, 300, 190);
}
else
{
eval(originalScript);
}
}

$(pagerCellSelector +
" input[type='button'][class^='rgPage']"
).each(
function
() {
var
a =
this
.onclick;
var
b = String(a);
a = b.substring(21, b.length - 1);
this
.onclick =
function
() {
return
confirmOnPage(a);
}
});
might have been an easier way to do this, but i couldn't figure out any other way.

The whole reason I had to substring was to strip out the following javascript code along with the ending bracket...But depending on what browser is being used, different code gets added!
IE7 put it the following before the original script:
function anonymous()
{
... original postback event
}
above required stripping by starting at index 22
while IE 8 did this:
function onclick()
{
... original postback event
}
above required stripping by starting at index 21
since the lengths are off by 1, my original solution only worked for IE8, not IE7. So i've since added a check to see which is which and then determine the starting point for the substring.. And, firefox actually adds something different form IE's, being "onclick(event) { ...". But our users do not use firefox for this particular site, so I don't have to worry about it for now. I imagien other browsers do something even different...
Sigh, obviously this is not an ideal solution. Well, since I won't be able to get the browsers to interpret the javascript code identically, is there a better fix for my issue?
function
pageLoad(sender, args)
{
var
$ = $telerik.$;
var
pagerCellSelector =
"#<%= RadGrid1.ClientID %> td.rgPagerCell"
;
$(pagerCellSelector +
" a[href^='javascript:__doPostBack']"
).each(
function
()
{
this
.href = String.format(
"javascript:confirmOnPage(\"{0}\");void(0)"
,
this
.href.replace(
"javascript:"
,
""
));
});
$(pagerCellSelector +
" input[type='submit'][class^='rgPage']"
).each(
function
()
{
this
.onclick =
function
()
{
return
confirmOnPage(
"__doPostBack('"
+
this
.name +
"', '')"
);
}
});
}
function
confirmOnPage(originalScript)
{
var
confirmText =
"Are you sure you want to page away?"
;
radconfirm(confirmText,
function
(ret)
{
if
(originalScript)
{
if
(ret)
{
eval(originalScript);
}
}
else
{
return
ret;
}
},
"300px"
,
"140px"
,
null
,
"Navigate away from current page?"
);
return
false
;
}
It should be working with all supported browsers.
Veli
the Telerik team

The only other thing is, with the code above, if a user is already on the first page and they click the First Page, or Previous page buttons, it acts like it is paging, even though it obviously doesn't since it's already on the first page. Acts similarly when user is on the last page. and, I obviously do not want it to run the confirm box when this is the stiuation either. to compensate for this, I altered the code as below:
function
pageLoad(sender, args) {
var
$ = $telerik.$;
var
pagerCellSelector =
"#<%= Grid.ClientID %> td.rgPagerCell"
;
var
tableView = $find(
'<%= Grid.ClientID %>'
).get_masterTableView();
var
currentPageIndex = tableView.get_currentPageIndex();
var
pageCount = tableView.get_pageCount();
var
endPage = pageCount -1; // because 0 indexed
if
(pageCount > 1) {
$(pagerCellSelector +
" a[href^='javascript:__doPostBack']"
).each(
function
() {
this
.href = String.format(
"javascript:confirmOnPage(\"{0}\");void(0)"
,
this
.href.replace(
"javascript:"
,
""
));
});
$(pagerCellSelector +
" input[type='button'][class^='rgPage']"
).each(
function
() {
if
((currentPageIndex == 0 && (
this
.className ==
"rgPageFirst"
||
this
.className ==
"rgPagePrev"
)) ||
(currentPageIndex == endPage && (
this
.className ==
"rgPageLast"
||
this
.className ==
"rgPageNext"
))
) {
this
.onclick =
function
() {
return
false
;
}
}
else
{
this
.onclick =
function
() {
return
confirmOnPage(
"__doPostBack('"
+
this
.name +
"', '')"
);
}
}
});
}
//end pageCnt > 1
}
my question is, is my method the best way? Or is there a more optimum solution you could provide? I mean, if future telerik upates alter the className for the pager buttons, it could cause my code to break..although I guess it would anyway since the code you provided actually targets things by className as well.
note: I also added in a check to determin if pageCount is 1, because if there's only one page, I don't need do apply any of the code...
thanks!
edit: also, is there a better way to atleast determine which button was clicked rather than by className ?) Thanks again.
Veli
the Telerik team

Great stuff. Looking for support to potentially block pagesizechange & sorting - client side.
Is this possible too?
tx
Sure, both commands can be blocked using the client-side OnCommand event of the grid:
<
telerik:RadGrid
ID
=
"RadGrid1"
runat
=
"server"
AllowSorting
=
"true"
AllowPaging
=
"true"
>
<
ClientSettings
>
<
ClientEvents
OnCommand
=
"gridCommand"
/>
</
ClientSettings
>
</
telerik:RadGrid
>
<
script
type
=
"text/javascript"
>
function gridCommand(sender, args)
{
if (args.get_commandName() == "Sort")
{
//this is where you catch the Sort command on the
//client before a postback. To cancel the command,
//use args.set_cancel(true)
}
if (args.get_commandName() == "PageSize")
{
//this is where you catch the PageSize command on the
//client before a postback. To cancel the command,
//use args.set_cancel(true)
}
}
</
script
>
Greetings,
Veli
the Telerik team
Browse the vast support resources we have to jump start your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.

tried that on the example project attached, but after the set_cancel(true) on the 'PageSize' command, the 'pager' display section is gone!
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MyWebUserControl.ascx.cs"
Inherits="MyWebUserControl" %>
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
<
telerik:RadScriptBlock
runat
=
"server"
>
<
script
type
=
"text/javascript"
>
function onCommand(sender, args) {
debugger;
if (args.get_commandName() == "Sort") {
//this is where you catch the Sort command on the
//client before a postback.
args.set_cancel(true)
}
if (args.get_commandName() == "PageSize") {
//this is where you catch the PageSize command on the
//client before a postback.
args.set_cancel(true)
}
}
function OnGridCreated(sender, args) {
debugger;
var $ = $telerik.$;
var pagerCellSelector = "#<%= RadGrid1.ClientID %> td.rgPagerCell";
var tableView = $find('<%= RadGrid1.ClientID %>').get_masterTableView();
var currentPageIndex = tableView.get_currentPageIndex();
var pageCount = tableView.get_pageCount();
var endPage = pageCount - 1; // because 0 indexed
if (pageCount > 1) {
$(pagerCellSelector + " a[href^='javascript:__doPostBack']").each(function () {
this.href = String.format("javascript:confirmOnPage(\"{0}\");void(0)", this.href.replace("javascript:", ""));
});
$(pagerCellSelector + " input[type='submit'][class^='rgPage']").each(function () {
if ((currentPageIndex == 0 && (this.className == "rgPageFirst" || this.className == "rgPagePrev")) ||
(currentPageIndex == endPage && (this.className == "rgPageLast" || this.className == "rgPageNext"))
) {
this.onclick = function () {
return false;
}
}
else {
this.onclick = function () {
return confirmOnPage("__doPostBack('" + this.name + "', '')");
}
}
});
} //end pageCnt > 1
}
function confirmOnPage(originalScript) {
debugger;
if (rik == 1) {
var confirmText = "Are you sure you want to page away?";
radconfirm(confirmText, function (ret) {
if (originalScript) {
if (ret) {
eval(originalScript);
}
}
else {
return ret;
}
}, "300px", "140px", null, "Navigate away from current page?");
return false;
}
else {
eval(originalScript);
}
}
</
script
>
</
telerik:RadScriptBlock
>
<
telerik:RadWindowManager
ID
=
"RadWindowManager1"
runat
=
"server"
/>
<
telerik:RadGrid
runat
=
"server"
CssClass
=
"radGrid"
AllowPaging
=
"true"
AllowSorting
=
"true"
AllowFilteringByColumn
=
"true"
PageSize
=
"3"
ID
=
"RadGrid1"
>
<
ClientSettings
>
<
ClientEvents
OnGridCreated
=
"OnGridCreated"
OnCommand
=
"onCommand"
/>
</
ClientSettings
>
</
telerik:RadGrid
>
Blur from the TextBox<
asp:TextBox
runat
=
"server"
CssClass
=
"textbox"
></
asp:TextBox
>
I can confirm that. It seems RadGrid's OnCommand client event is too late to prevent changes to the grid pager associated with changing the page size. You can take an alternative approach for canceling the PageSize event:
1. Use RadGrid's OnGridCreated client event to find the pager combo's client component.
2. Hook a js handler to the combo's client-side OnSelectedIndexChanging event.
3. Cancel the event if required there
Here is a sample:
<
telerik:RadGrid
ID
=
"RadGrid1"
runat
=
"server"
Width
=
"800px"
OnNeedDataSource
=
"RadGrid1_NeedDataSource"
AllowSorting
=
"true"
AllowPaging
=
"true"
>
<
ClientSettings
>
<
ClientEvents
OnCommand
=
"gridCommand"
OnGridCreated
=
"gridCreated"
/>
</
ClientSettings
>
</
telerik:RadGrid
>
<
script
type
=
"text/javascript"
>
function gridCreated(sender, args)
{
var pageSizeCombo = $telerik.findControl(sender.get_masterTableView().get_element(), "PageSizeComboBox");
if (pageSizeCombo)
{
pageSizeCombo.add_selectedIndexChanging(function(sender, args)
{
//this method will fire before the combo changes the
//page size in the grid pager. You can cancel this event
args.set_cancel(true);
});
}
}
function gridCommand(sender, args)
{
if (args.get_commandName() == "Sort")
{
//this is where you catch the Sort command on the
//client before a postback. To cancel the command,
//use args.set_cancel(true)
}
}
</
script
>
Let me know how this works for you.
Veli
the Telerik team
Thank you for being the most amazing .NET community! Your unfailing support is what helps us charge forward! We'd appreciate your vote for Telerik in this year's DevProConnections Awards. We are competing in mind-blowing 20 categories and every vote counts! VOTE for Telerik NOW >>

Tx for that.
A consequence of adding ClientEvent OnCommand is that the onclick event is activated on the paging anchor numeric fields (see also attached screenshot):
Onclick="if(!$find('ct100_UP_Body_DeplValidationSheet_RGValidation_ct100').page('2')) return false;"
The result is that the confirmOnPage javascript code is not executed, and thus the paging action cannot be blocked.
Putting the onclick event to 'null' (at the same time when the href event is changed, 'fixes' the issue.
Can you confirm that the onclick event is there to support the OnCommand client event (which I don't need anyway) and I don't break any other functionality.
Also, is there a reason why this onclick event removes the href hack?
tx,
Rik
I can confirm that. When you attach to the OnCommand client event in RadGrid, RadGrid ensures that any command you fire will cause the client-side OnCommand event to be raised. To facilitate this, RadGrid exchanges postback behavior of its controls to use internal javascript function calls instead. This is why your page buttons get onclick handlers that perform the postback, instead of evaluating the href attribute. With this setup, you are advised to use the OnCommand event to execute any custom code before paging or other grid commands. You can use OnCommand to cancel any command (setting args.set_cancel(true)), including paging. Contrary, replacing the href attribute in page buttons is not supported and we cannot guarantee proper control behavior when you alter the behavior of link buttons in this way.
Greetings,
Veli
the Telerik team
Thank you for being the most amazing .NET community! Your unfailing support is what helps us charge forward! We'd appreciate your vote for Telerik in this year's DevProConnections Awards. We are competing in mind-blowing 20 categories and every vote counts! VOTE for Telerik NOW >>

You stated:
Hi Rik,
I can confirm that. It seems RadGrid's OnCommand client event is too late to prevent changes to the grid pager associated with changing the page size. You can take an alternative approach for canceling the PageSize event:
1. Use RadGrid's OnGridCreated client event to find the pager combo's client component.
2. Hook a js handler to the combo's client-side OnSelectedIndexChanging event.
3. Cancel the event if required there
And that's exactly my experience with the OnCommand="Page", the pageindex indication on the pager changes if set_cancel() is executed, leading to confusion.
tx & br,
Rik
Let me try to clarify the confusion. The 2 main differentiating points are:
1. OnCommand is used to hook up and cancel before almost any server-side event is executed, i.e. before RadGrid posts the page. RadGrid's OnCommand event is the recommended event to use for dealing with most of RadGrid's commands. This includes the Page command, but not the PageSizeChanged command.
2. For canceling the PageSizeChanged command, the OnCommand grid event does not work. For this particular command (PageSizeChanged), you need to use the GridCreated event, find the PageSizeComboBox instance, hook to its client-side selectedIndexChanged event and cancel the event there.
Sorry if I have confused you. Does it get any clearer?
Veli
the Telerik team
Thank you for being the most amazing .NET community! Your unfailing support is what helps us charge forward! We'd appreciate your vote for Telerik in this year's DevProConnections Awards. We are competing in mind-blowing 20 categories and every vote counts! VOTE for Telerik NOW >>

I understood that. The part that you missed (or I did not explain well) is: the pageindex indication on the pager changes if set_cancel() is executed, leading to confusion.
If you execute below code, it's showing 4 pages. If you click on page 3, the confirmOnPage javascript function is executed (args.get_commandName() == "Page"), if you cancel out, the pagelink for page 3 remains active, is thus not undone. There's the problem...
<%
@ Page Language="C#" %>
<!
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%
@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
<
script runat="server">
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
RadGrid1.DataSource =
new string[] {
"Item1", "Item1", "Item1", "Item1",
"Item1", "Item1", "Item1", "Item1",
"Item1", "Item1", "Item1", "Item1",
"Item1", "Item1", "Item1", "Item1"
};
}
</
script>
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<title></title>
</
head>
<
body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<telerik:RadGrid ID="RadGrid1" AllowPaging="True" runat="server" EnableColumnsViewState="false"
ShowStatusBar="true" Skin="WebBlue" OnNeedDataSource="RadGrid1_NeedDataSource"
AllowSorting="true" Width="100%" CellSpacing="0"
GridLines="None">
<MasterTableView PageSize="5" AllowPaging="true" TableLayout="Fixed">
<Columns>
<telerik:GridBoundColumn DataField="Item" HeaderText="ID" ItemStyle-Width="50px" UniqueName="Item">
<ItemStyle Width="50px" />
</telerik:GridBoundColumn>
</Columns>
<HeaderStyle Height="32px" />
<PagerStyle AlwaysVisible="false" Height="50px" VerticalAlign="Top" Mode="NextPrevAndNumeric" />
<NoRecordsTemplate>
<asp:Label ID="LBLNoValidationRecords" runat="server" Text="No validation ercords found for your selection" />
</NoRecordsTemplate>
<EditFormSettings>
<EditColumn FilterControlAltText="Filter EditCommandColumn column">
</EditColumn>
</EditFormSettings>
</MasterTableView>
<ClientSettings AllowColumnsReorder="true" ReorderColumnsOnClient="true" AllowColumnHide="true" >
<ClientEvents OnCommand="gridCommand" />
<Selecting AllowRowSelect="false" />
<Resizing AllowRowResize="false" EnableRealTimeResize="True" ResizeGridOnColumnResize="true"
AllowColumnResize="True"></Resizing>
</ClientSettings>
</telerik:RadGrid>
<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
<script type="text/javascript">
function pageLoad(sender, args)
{
var grid = $find('<%= RadGrid1.ClientID %>');
var tfoot = grid.get_element().getElementsByTagName("tfoot")[0];
var anchors = tfoot.getElementsByTagName("a");
// for (var i = 0, length = anchors.length; i < length; i++)
// {
// var anchor = anchors[i];
// var href = anchor.href;
// if (href.indexOf("javascript:__doPostBack") > -1)
// {
// anchor.href = String.format("javascript:confirmOnPage(\"{0}\")", href.replace("javascript:", ""));
// anchor.onclick = null;
// }
// }
var inputs = tfoot.getElementsByTagName("input");
for (var i = 0, length = inputs.length; i < length; i++)
{
var input = inputs[i];
if (input.type == "submit" && input.className.indexOf("rgPage") > -1)
{
input.onclick =
function()
{
return confirmOnPage("");
}
}
}
}
function confirmOnPage(originalScript)
{
var ret = confirm("Are you sure you want to page away?");
if (originalScript)
{
if (ret)
{
eval(originalScript);
}
}
else
{
return ret;
}
}
function gridCommand(sender, args) {
// debugger;
if (args.get_commandName() == "Sort") {
//this is where you catch the Sort command on the
//client before a postback.
if (!confirmOnPage()) {
args.set_cancel(
true)
}
}
if (args.get_commandName() == "Page") {
//this is where you catch the Sort command on the
//client before a postback.
if (!confirmOnPage()) {
args.set_cancel(
true)
}
}
}
</script>
</telerik:RadCodeBlock>
</div>
</form>
</
body>
</
html>
I am currently researching a workaround for this. Let me get back to you with whatever I find.
Greetings,
Veli
the Telerik team
Thank you for being the most amazing .NET community! Your unfailing support is what helps us charge forward! We'd appreciate your vote for Telerik in this year's DevProConnections Awards. We are competing in mind-blowing 20 categories and every vote counts! VOTE for Telerik NOW >>
Here is one workaround you can use to manually revert the pager to the last changed page index:
//to store the last page index
var
lastIndex;
//fired after page load - use to save the last changed index
function
pageLoad()
{
lastIndex = $find(
"RadGrid1"
).get_masterTableView().get_currentPageIndex();
}
//the OnCommand client event handler
function
gridCommand(sender, args)
{
//cancel the command
args.set_cancel(
true
);
//rever the pager to the last saved value
//the last parameter specifies that the control should not postback
args.get_tableView().set_currentPageIndex(lastIndex,
true
);
}
With the above approach, at every point, we know the last changed page index in RadGrid. Now, whenever we need to cancel a command in RadGrid, we revert the pager to the last saved page index without posting the page. Thus, the pager state is kept consistent.
Veli
the Telerik team
Thank you for being the most amazing .NET community! Your unfailing support is what helps us charge forward! We'd appreciate your vote for Telerik in this year's DevProConnections Awards. We are competing in mind-blowing 20 categories and every vote counts! VOTE for Telerik NOW >>