interviews.dotnetthread.com

↑ Grab this Headline Animator

Monday, March 2, 2009

Enable browser back and forward button support for Gridview paging and sorting in ASP.NET AJAX using jQuery.



Introduction:
The Article will demonstrate how to enable browser back and forward button support for GridView paging and sorting in ASP.NET AJAX using jQuery History plugin. jQuery is popular and widely used Javascript library and will take care of browser compatibility for our script.

Description:
Let’s see how to maintain browser history for GridView paging and sorting in using AJAX using jQuery History plug-in (which allows dynamic pages to create page states and easily recall them when user navigation occurs).


Before starting please download jQuery library from here and jQuery History plug in from here.

• Create new Ajax Enabled Website using Visual Studio templates.

• Add a new folder to it in solution explorer name it “jQuery” and add jQuery library and History plug in JavaScript files to this folder. You can name these files as you like.


• Add reference to both JavaScript files (jQuery.js and history.js) into Default.aspx page under head tag.



<script type="text/javascript" src="jQuery/jquery.js"></script>

<script type="text/javascript" src="jQuery/history.js"></script>



• We need a textbox/hidden field to store value (hash value) that we need to pass to backend method,and asp button control with Onclick event which will be used to trigger the Update Panel. As we don’t need to show this textbox and button on the page to the user we will just hide these using CSS.


<asp:TextBox ID="text" runat="server" style="display:none;"></asp:TextBox>
<asp:Button ID="button" runat="server" OnClick="button_Click" style="display:none;"/>



• Add update panel to .aspx page and include GridView with OnSorting and OnPageIndexChanged events. Add Asynchronous post back trigger to the Update Panel for hidden button click event.

<asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None" AllowPaging="true"
AllowSorting="true" OnSorting="GridView1_Sorting" OnPageIndexChanged="GridView1_PageIndexChanged">
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:BoundField DataField="CompanyId" HeaderText="CompanyId" SortExpression="CompanyId" />
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
<asp:BoundField DataField="SectorName" HeaderText="SectorName" SortExpression="SectorName" />
</Columns>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:sampleConnectionString %>"
SelectCommand="SELECT DISTINCT [CompanyId], [CompanyName], [SectorName] FROM [abc]">
</asp:SqlDataSource>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="button" EventName="Click" />
</Triggers>
</asp:UpdatePanel>


• Add a Javascript function addToHistory to the aspx page to add history to the browser with input hash value.

• In GridView sorting event handler register client script block with script manager to call addToHistory JavaScript method by passing SortDirection and Sort field as a hash value.

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
// Create the history state for Direction and Expression
ScriptManager.RegisterStartupScript(this, this.GetType(), "AddHistory", "addToHistory('SortDirection=" + e.SortDirection.ToString() + "&&SortExpression=" + e.SortExpression + "');", true);
}


• In GridView OnPageIndexChanged event handler register client script block with script manager to call addToHistory JavaScript method by passing PageIndex as a hash value.

protected void GridView1_PageIndexChanged(object sender, EventArgs e)
{
// To check if post back is Asynchronous
if (ScriptManager1.IsInAsyncPostBack)
{
//To add History point with gridview selected page index value.
ScriptManager.RegisterStartupScript(this, this.GetType(), "AddHistory", "addToHistory('PageIndex=" + GridView1.PageIndex.ToString() + "');", true);
}
}


• Now as the history points are being added to the browser user will be able to move forward or backward using browser buttons, Add the below code to register a function to be called for every user navigation in which we will set hash value (history point value) into hidden field and raise hidden button click event using doPostBack method for it.

protected void button_Click(object sender, EventArgs e)
{
string entryName = text.Text;
if (entryName.Contains("SortDirection") && entryName.Contains("SortExpression"))
{
string[] splitter = new String[1];
splitter[0] = "&&";
string[] text1 = entryName.Split(splitter, StringSplitOptions.None);
string sortExpression = text1[1].Replace("SortExpression=", "");
string strSortDirection = text1[0].Replace("SortDirection=", "");
SortDirection sortDirection = (SortDirection)Enum.Parse(typeof(SortDirection), strSortDirection);

// Sort the grid according to the sort information in the history state
GridView1.Sort(sortExpression, sortDirection);
}

// Get GridView PagIndex from history
string pageIndex = string.Empty;
if (entryName.Contains("PageIndex"))
{
pageIndex = entryName.Replace("PageIndex=", "");
}
if (string.IsNullOrEmpty(pageIndex))
{
GridView1.PageIndex = 0;
}
else
{
GridView1.PageIndex = Convert.ToInt32(pageIndex);
}
}


• Now finally in the button click event handler we need to get the history point value from hidden textbox/hidden field using which we will bind the GridView the appropriate PageIndex, SortDirection and SortField. Hence updating Update Panel content with browser history value.

<script type="text/javascript">

$(document).ready(function()
{
$(window).history(function(e, hash)
{
var obj = document.getElementById("<%= text.ClientID %>");
obj.value=hash;
__doPostBack("<%= button.ClientID %>","");
});
});
</script>


Download the Source Code for this article here.


Note: You have to change connection string in Web.config and also configure sqldatasource with local db table for running the sample application.

Submit this story to DotNetKicks

No comments:

Post a Comment

Post your comments/questions/feedback for this Article.

 

Latest Articles