This is a migrated thread and some comments may be shown as answers.

Ajaxified Radgrid pager posts back twice on page index change (Randomly)

10 Answers 218 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Ankit
Top achievements
Rank 1
Ankit asked on 19 Oct 2011, 09:36 PM
Hi

I have created a simple ajaxified radgrid. Everything works fine except that sometimes when I paginate (change page index), it triggers the OnCommand client event twice. And that too randomly. There is no fixed index at which it happens and that makes it even more difficult for me to identify the problem.  For example if it happens when I click page 5, there are 2 postbacks.... the first one passes the correct pageIndex (4) and loads the proper data on the grid.... but the second post back passes pageIndex as 0 so the grid displays page 1 data.

My pagesize is 10 and I have more than 100 pages.

Here is my Aspx:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default3.aspx.vb" Inherits="Default3" %>
 
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head runat="server">
    <title>Event Log</title>
    <style type="text/css">
        .RadLoadingPanel { top: 0px; right: 0px; position: fixed; background-color: #EBEBEB; }
        .RadLoadingPanel img { vertical-align: middle; margin: 2px; }
    </style>
 
    <script type="text/javascript" src="JS/jquery-1.6.4.min.js"></script>
 
    <script type="text/javascript" src="JS/json2.js"></script>
 
    <telerik:RadCodeBlock runat="server" ID="rc">
 
        <script type="text/javascript">
            var commandName = "";
            var tableView = null;
            function pageLoad()
            {
                setTimeout('LoadGrid();', 1);
            }
 
            function LoadGrid()
            {
                tableView = $find("<%= rg.ClientID %>").get_masterTableView();
                commandName = "Load"
                executeMethod("Default3.aspx", "GetDataAndCount", getRequestData(tableView), updateGrid);
            }
 
            function gridOnCommand(sender, args)
            {
                if (args.get_commandName() != "PageSize")
                {
                    args.set_cancel(true);
                    LoadGrid();
                }
            }
 
 
            function FailMessage()
            {
                alert('fail');
            }
 
            function updateGrid(result)
            {
                tableView.set_dataSource(result.d.Data);
                tableView.set_virtualItemCount(result.d.Count);
                tableView.dataBind();
            }
 
 
            function getRequestData(tableView)
            {
                return JSON.stringify({
                    "startIndex": tableView.get_currentPageIndex(),
                    "maximumRows": tableView.get_pageSize(),
                    "eID": $('#<%=txtEventID.ClientID %>').val(),
                    "fDate": $find("<%= rdFrom.ClientID %>").get_selectedDate(),
                    "tDate": $find("<%= rdTo.ClientID %>").get_selectedDate(),
                    "sortExpression": tableView.get_sortExpressions().toString(),
                    "filterExpression": tableView.get_filterExpressions().toDynamicLinq()
 
                });
            }
 
            function executeMethod(location, methodName, methodArguments, onSuccess, onFail)
            {
                $.ajax({
                    type: "POST",
                    url: location + "/" + methodName,
                    data: methodArguments,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: onSuccess,
                    fail: onFail,
                    beforeSend: function()
                    {
                        // Handle the beforeSend event  
                        $("#<%=RadAjaxLoadingPanel1.ClientID %>").show()
                    },
                    complete: function()
                    {
                        // Handle the complete event  
                        $("#<%=RadAjaxLoadingPanel1.ClientID %>").hide()
                    }
 
                });
            }
        </script>
 
    </telerik:RadCodeBlock>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <telerik:RadScriptManager ID="RadScriptManager1" runat="server">
            <Scripts>
                <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js">
                </asp:ScriptReference>
                <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js">
                </asp:ScriptReference>
                <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.js">
                </asp:ScriptReference>
            </Scripts>
        </telerik:RadScriptManager>
        <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" CssClass="RadLoadingPanel"
            IsSticky="True" EnableEmbeddedSkins="false" EnableAjaxSkinRendering="false">
            <asp:Image runat="server" ID="imgLoading" ImageUrl="ajax-loader.gif" AlternateText="Loading..." />
            <span>Loading...</span>
        </telerik:RadAjaxLoadingPanel>
        <table>
            <tr>
                <th>
                    From Date
                </th>
                <td>
                    <telerik:RadDatePicker ID="rdFrom" runat="server">
                    </telerik:RadDatePicker>
                </td>
            </tr>
            <tr>
                <th>
                    To Date
                </th>
                <td>
                    <telerik:RadDatePicker ID="rdTo" runat="server">
                    </telerik:RadDatePicker>
                </td>
            </tr>
            <tr>
                <th>
                    Event ID
                </th>
                <td>
                    <asp:TextBox ID="txtEventID" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <th>
                </th>
                <td>
                    <a href="javascript://" onclick="LoadGrid();return false;">Search</a>
                </td>
            </tr>
        </table>
        <br />
        <br />
        <telerik:RadAjaxPanel ID="rp" runat="server" LoadingPanelID="RadAjaxLoadingPanel1">
            <telerik:RadGrid ID="rg" runat="server" AutoGenerateColumns="False" AllowPaging="True"
                CellSpacing="0" GridLines="None" AllowSorting="true" >
                <ClientSettings EnableRowHoverStyle="True" >
                    <ClientEvents OnCommand="gridOnCommand"  />
                </ClientSettings>
                <MasterTableView AllowNaturalSort="False" AllowMultiColumnSorting="false">
                    <Columns>
                        <telerik:GridBoundColumn DataField="EventID" HeaderText="Event ID">
                            <ItemStyle Width="10%" />
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="EventDate" HeaderText="Event Date" DataFormatString="{0:M/dd/yy  h:mm tt}"
                            DataType="System.DateTime">
                            <ItemStyle Width="15%" />
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="EventDesc" HeaderText="Description" AllowSorting="false">
                        </telerik:GridBoundColumn>
                    </Columns>
                    <PagerStyle AlwaysVisible="True"></PagerStyle>
                </MasterTableView>
            </telerik:RadGrid>
        </telerik:RadAjaxPanel>
    </div>
    </form>
</body>
</html>

And here is the VB Code:
Imports System.Web.Services
Imports System.Data
 
Partial Class Default3
    Inherits System.Web.UI.Page
 
    <WebMethod(True)> _
 Public Shared Function GetDataAndCount(ByVal startIndex As Integer, ByVal maximumRows As Integer, ByVal eID As String, ByVal fDate As Nullable(Of Date), ByVal tDate As Nullable(Of Date)) As Dictionary(Of String, Object)
        Dim data As New Dictionary(Of String, Object)()
        Using dc As New DataClassesDataContext
 
            'dc.Log = Console.Out
 
            Dim EL = From e In dc.EventLogs _
               Select e.EventID, e.EventDate, e.EventDesc _
            Order By EventDate Descending
 
            If IsNumeric(eID) Then
                EL = EL.Where(Function(e) e.EventID = CLng(eID))
            End If
 
            If fDate.HasValue Then
                EL = EL.Where(Function(e) e.EventDate >= fDate.Value)
            End If
 
            If tDate.HasValue Then
                EL = From e In EL _
                  Where e.EventDate < tDate.Value.AddDays(1)
            End If
 
            data.Add("Data", EL.Skip(startIndex * maximumRows).Take(maximumRows).ToList())
            data.Add("Count", EL.Count)
            Return data
        End Using
    End Function
 
End Class


P.S: I am using v2011.2.915.35 of Telerik and this happens both in Firefox and IE.

10 Answers, 1 is accepted

Sort by
0
Vasil
Telerik team
answered on 24 Oct 2011, 08:17 AM
Hi Ankit,

It is very strange that the OnCommand is fired twice. Is the same problem happens when you turn off the ajax? Is there difference in the args of gridOnCommand in the second call?

All the best,
Vasil
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now
0
Ankit
Top achievements
Rank 1
answered on 24 Oct 2011, 03:40 PM
Hi Vasil

Well I wanted to use Ajax specifically. But I dont think it happens if I turn it off. I have used paging in non-ajax pages and it works perfectly fine. And there is no difference in the args of OnCommand in the second call. The only difference is, the page index is reset and it moves to page 1.
Strange thing is it happens randomly(at random pages) as I mentioned before.

Any help will be greatly appreciated!
0
Vasil
Telerik team
answered on 26 Oct 2011, 02:20 PM
Hi Ankit,

I was unable to reproduce the problem in sample page. Could you share runnable project that we could test? Or if you have your site online I could try to test it there and see if the problem is in the client side api.

Best wishes,
Vasil
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now
0
Ankit
Top achievements
Rank 1
answered on 26 Oct 2011, 08:21 PM
Hi Vasil

I have uploaded that sample code on this link:

http://66.64.17.108/AjaxSite

I have tested it rigorously on FireFox, IE and Chrome and the frequency of occurrence decreases in that order with the least occurrence in Chrome.

Thanks again for your reply.

Here are the code files..

Aspx Code:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default3.aspx.vb" Inherits="Default3" %>
 
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head runat="server">
    <title>Event Log</title>
    <style type="text/css">
        .RadLoadingPanel { top: 0px; right: 0px; position: fixed; background-color: #EBEBEB; }
        .RadLoadingPanel img { vertical-align: middle; margin: 2px; }
    </style>
 
    <script type="text/javascript" src="JS/jquery-1.6.4.min.js"></script>
 
    <script type="text/javascript" src="JS/json2.js"></script>
 
    <telerik:RadCodeBlock runat="server" ID="rc">
 
        <script type="text/javascript">
            var commandName = "";
            var tableView = null;
            function pageLoad()
            {
                setTimeout('LoadGrid();', 1);
            }
 
            function LoadGrid()
            {
                tableView = $find("<%= rg.ClientID %>").get_masterTableView();
                commandName = "Load"
                executeMethod("Default3.aspx", "GetDataAndCount", getRequestData(tableView), updateGrid);
            }
 
            function gridOnCommand(sender, args)
            {
                if (args.get_commandName() != "PageSize")
                {
                    args.set_cancel(true);
                    LoadGrid();
                }
            }
 
 
            function FailMessage()
            {
                alert('fail');
            }
 
            function updateGrid(result)
            {
                tableView.set_dataSource(result.d.Data);
                tableView.set_virtualItemCount(result.d.Count);
                tableView.dataBind();
            }
 
 
            function getRequestData(tableView)
            {
                return JSON.stringify({
                    "startIndex": tableView.get_currentPageIndex(),
                    "maximumRows": tableView.get_pageSize(),
                    "eID": $('#<%=txtEventID.ClientID %>').val(),
                    "fDate": $find("<%= rdFrom.ClientID %>").get_selectedDate(),
                    "tDate": $find("<%= rdTo.ClientID %>").get_selectedDate(),
                    "sortExpression": tableView.get_sortExpressions().toString(),
                    "filterExpression": tableView.get_filterExpressions().toDynamicLinq()
 
                });
            }
 
            function executeMethod(location, methodName, methodArguments, onSuccess, onFail)
            {
                $.ajax({
                    type: "POST",
                    url: location + "/" + methodName,
                    data: methodArguments,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: onSuccess,
                    fail: onFail,
                    beforeSend: function()
                    {
                        // Handle the beforeSend event  
                        $("#<%=RadAjaxLoadingPanel1.ClientID %>").show()
                    },
                    complete: function()
                    {
                        // Handle the complete event  
                        $("#<%=RadAjaxLoadingPanel1.ClientID %>").hide()
                    }
 
                });
            }
 
 
            function gridRowBound(sender, args)
            {
                var EventID = args.get_item().get_dataItem().EventID;
                var hlView = args.get_item().findElement("hlView");
                $(hlView).unbind('click').click(function()
                {
                    alert('EventID is ' + EventID);
                });
 
                var rm = $find(args.get_item().findElement("rm").id);
                var itemView = rm.findItemByText("View")
                //itemView.set_navigateUrl("javascript:alert('View Event " + EventID + "');");
 
                $(itemView.get_element()).find("a").unbind('click').click(function()
                {
                    alert('View EventID is ' + EventID);
                });
 
                var itemEdit = rm.findItemByText("Edit")
                itemEdit.set_navigateUrl("javascript:alert('Edit Event " + EventID + "');");
 
            }
        </script>
 
    </telerik:RadCodeBlock>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <telerik:RadScriptManager ID="RadScriptManager1" runat="server">
            <Scripts>
                <%--<asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js">
                </asp:ScriptReference>
                <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js">
                </asp:ScriptReference>
                <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.js">
                </asp:ScriptReference>--%>
            </Scripts>
        </telerik:RadScriptManager>
        <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" CssClass="RadLoadingPanel"
            IsSticky="True" EnableEmbeddedSkins="false" EnableAjaxSkinRendering="false">
            <asp:Image runat="server" ID="imgLoading" ImageUrl="ajax-loader.gif" AlternateText="Loading..." />
            <span>Loading...</span>
        </telerik:RadAjaxLoadingPanel>
        <table>
            <tr>
                <th>
                    From Date
                </th>
                <td>
                    <telerik:RadDatePicker ID="rdFrom" runat="server">
                    </telerik:RadDatePicker>
                </td>
            </tr>
            <tr>
                <th>
                    To Date
                </th>
                <td>
                    <telerik:RadDatePicker ID="rdTo" runat="server">
                    </telerik:RadDatePicker>
                </td>
            </tr>
            <tr>
                <th>
                    Event ID
                </th>
                <td>
                    <asp:TextBox ID="txtEventID" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <th>
                </th>
                <td>
                    <%--<a href="javascript://" onclick="LoadGrid();return false;">Search</a>--%>
                </td>
            </tr>
        </table>
        <br />
        <br />
        <telerik:RadAjaxPanel ID="rp" runat="server" LoadingPanelID="RadAjaxLoadingPanel1">
            <telerik:RadGrid ID="rg" runat="server" AutoGenerateColumns="False" AllowPaging="True"
                CellSpacing="0" GridLines="None" AllowSorting="true" >
                <ClientSettings EnableRowHoverStyle="True" >
                    <ClientEvents OnCommand="gridOnCommand"  />
                </ClientSettings>
                <MasterTableView AllowNaturalSort="False" AllowMultiColumnSorting="false">
                    <Columns>
                        <telerik:GridBoundColumn DataField="EventID" HeaderText="Event ID" ItemStyle-Width="25%" />
                        <telerik:GridBoundColumn DataField="EventDate" HeaderText="Event Date" DataFormatString="{0:M/dd/yy  h:mm tt}" DataType="System.DateTime" ItemStyle-Width="25%" />
                    </Columns>
                    <PagerStyle AlwaysVisible="True" ></PagerStyle>
                </MasterTableView>
            </telerik:RadGrid>
        </telerik:RadAjaxPanel>
    </div>
    </form>
</body>
</html>


VB Code:
Imports System.Web.Services
Imports System.Data
 
Partial Class Default3
    Inherits System.Web.UI.Page
 
 
    <WebMethod(True)> _
       Public Shared Function GetDataAndCount(ByVal startIndex As Integer, ByVal maximumRows As Integer, ByVal eID As String, ByVal fDate As Nullable(Of Date), ByVal tDate As Nullable(Of Date)) As Dictionary(Of String, Object)
        Dim data As New Dictionary(Of String, Object)()
        Using dc As New DataClassesDataContext
 
            'dc.Log = Console.Out
 
            Dim EL = From e In dc.EventLogs _
               Select e.EventID, e.EventDate _
            Order By EventDate Descending
 
            If IsNumeric(eID) Then
                EL = EL.Where(Function(e) e.EventID = CLng(eID))
            End If
 
            If fDate.HasValue Then
                EL = EL.Where(Function(e) e.EventDate >= fDate.Value)
            End If
 
            If tDate.HasValue Then
                EL = From e In EL _
                  Where e.EventDate < tDate.Value.AddDays(1)
            End If
 
 
 
            data.Add("Data", EL.Skip(startIndex * maximumRows).Take(maximumRows).ToList())
            data.Add("Count", EL.Count)
            Return data
        End Using
    End Function
 
 
    Protected Sub rg_NeedDataSource(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridNeedDataSourceEventArgs) 'Handles rg.NeedDataSource
        Dim i As Integer = 0
 
        Dim arr As New ArrayList
        For i = 0 To rg.PageSize - 1
            arr.Add(i)
        Next
 
        rg.DataSource = arr
 
    End Sub
End Class
0
Accepted
Vasil
Telerik team
answered on 27 Oct 2011, 07:17 AM
Hi Ankit,

The problem comes when you set set_virtualItemCount different to the previous one. This forces the grid to reset it's paging.
So in random time your database get's more records. For example they was 561424 in one moment and after the next paging they was 561426. So when this happens the pager get's reseted wtich is expected when changing the virtualItemCount.

Regards,
Vasil
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now
0
Ankit
Top achievements
Rank 1
answered on 27 Oct 2011, 03:22 PM
Thank you so much Vasil. It never struck me. This was a real time data so the virtual count kept increasing. Phew! Thanks a lot!
0
Ankit
Top achievements
Rank 1
answered on 03 Dec 2011, 12:01 AM
Hi Vasil,

Just wanted to know if there is a work around for not resetting the current page index on change of virtual count.

Here's my situation. I have a grid and I have a delete option for each row. Now when I delete a row from the 5th page, the vitualcount changes and the index is reset to page 1. I want to avoid that and stay on the same page index. Is there a way to do this? Or any work around? 

Thanks in advance!
Ankit
0
Vasil
Telerik team
answered on 05 Dec 2011, 08:52 AM
Hello Ankit,

You could use the get_currentPageIndex() and set_currentPageIndex() properties to get the page index before changing the virtual item count, and then to set the old one after the deleting the item.

Best wishes,
Vasil
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now
0
Ankit
Top achievements
Rank 1
answered on 12 Dec 2011, 05:57 PM
Hi Vasil

Thanks a lot...

Here is what I did for those interested...

This code is wired to the onCommand event of the grid.

if (args.get_commandArgument() != 0) {
        LoadGrid();
}
else {
        tableView.CurrentPageIndex = lastPagerIndex;
}

Noticed that when the grid resets the page index when virtual count is changed, the grid's args.get_commandArgument() becomes 0 instead of 1. When we page normally to the 1st page, its value is 1.
So this way we can distinguish between normal paging and reset and then load the grid accordingly.

0
Vasil
Telerik team
answered on 13 Dec 2011, 02:50 PM
Hi Ankit,

Thank you for sharing your solution with the community.

Kind regards,
Vasil
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now
Tags
Grid
Asked by
Ankit
Top achievements
Rank 1
Answers by
Vasil
Telerik team
Ankit
Top achievements
Rank 1
Share this question
or