CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Implementing Ajax History in Asp.Net 3.5 Ajax

By Suresh Kumar Goudampally
Posted On Mar 08, 2011
Article Rating:
Be first to rate
this article.
No of Comments: 1
Category: ASP.Net AJAX
Print this article.

Implementing Ajax History in Asp.Net 3.5 Ajax

 

Introduction

We know that when we open an internet site and move from one site to another site ­the browser maintains the history of pages visited so that when the user clicks on back and forward buttons on top he can go to the previous sites/pages visited. Earlier it was not possible to maintain history for asynchronous postbacks done using updatepanel and scriptmanager. Now the enhancements in Asp.Net 3.5 ajax extension made the developers job easy to maintain the browser history for asynchronous postbacks too. This article discusses how we can maintain the asynchronous postbacks history using the new features of scriptmanager.

 

Enabling Back button using Ajax History in ASP.Net AJAX

Let’s say we have a requirement we need to display the list of the employees with the page size 5 and the user wants paging to be done using ajax and maintain the ajax history.

1.      Take a GridView and bind it with data from sql server and implement the paging. The markup looks as below.

          <asp:GridView ID="GridView1" runat="server"

      AutoGenerateColumns="False" Width="631px" AllowPaging="True"

      onpageindexchanged="GridView1_PageIndexChanged"

onpageindexchanging="GridView1_PageIndexChanging" PageSize="5" CellPadding="4"

             ForeColor="#333333" GridLines="None">

          <RowStyle BackColor="#EFF3FB" />

      <Columns>

          <asp:BoundField DataField="sno" HeaderText="Sno" />

          <asp:BoundField DataField="empname" HeaderText="EmpName" />

      </Columns>

<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />

<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />

      <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

         <EditRowStyle BackColor="#2461BF" />

         <AlternatingRowStyle BackColor="White" />

    </asp:GridView>

The Code is as below:

   protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

            {

                GridView1.DataSource = GetDataSet();

                GridView1.DataBind();

            }

        }

        private DataSet GetDataSet()

        {

       SqlConnection con = new

SqlConnection("server=local;integrated security=true;database=master");

            DataSet ds = new DataSet();

SqlDataAdapter dta = new SqlDataAdapter("select

sno,empname from employees", con);

            dta.Fill(ds, "test");

            return ds;

        }

        protected void GridView1_PageIndexChanging(object sender,   

  GridViewPageEventArgs e)

        {

            GridView1.PageIndex = e.NewPageIndex;

            GridView1.DataSource = GetDataSet();

            GridView1.DataBind();

        }

              protected void GridView1_PageIndexChanged(object sender, EventArgs e)

        {

                       

     }

     

2.      Now run the application and check the output, user can click the paging buttons and traverse from page to other pages of GridView records. Also the browser history is maintained and user can move forward/backward using the backward and forward buttons. Check the screenshot where the history is maintained

Maintain History for enabling browser back button in AJAX

 

      Note: Here Ajax History is the page title given.

3.      But our requirement is to make paging requests as asynchronous post back. Let’s make the paging operations as asynchronous operations using Updatepanel and Scriptmanager. Drag the Scriptmanager to the page and place the GridView inside the Updatepanel. The sample markup looks as below.

     <asp:ScriptManager ID="ScriptManager1" runat="server">

      </asp:ScriptManager>

      <asp:UpdatePanel ID="UpdatePanel1" runat="server">

              <ContentTemplate>

      <asp:GridView ID="GridView1" runat="server"

      AutoGenerateColumns="False" Width="631px" AllowPaging="True"

      onpageindexchanged="GridView1_PageIndexChanged"

      onpageindexchanging="GridView1_PageIndexChanging" PageSize="5" CellPadding="4"

             ForeColor="#333333" GridLines="None">

          <RowStyle BackColor="#EFF3FB" />

      <Columns>

          <asp:BoundField DataField="sno" HeaderText="Sno" />

          <asp:BoundField DataField="empname" HeaderText="EmpName" />

      </Columns>

     <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

       <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />

       <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True"

       ForeColor="#333333" />

       <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

          <EditRowStyle BackColor="#2461BF" />

          <AlternatingRowStyle BackColor="White" />

    </asp:GridView>

    </ContentTemplate>

    </asp:UpdatePanel>    

4.      Now run the application and check the output by traversing page to page of GridView records. The postback is made asynchronous and the browser history doesn’t work. Check the screenshot for output.

       Enabling Back button using Ajax History in ASP.Net AJAX

5.      Now we need enable the Ajax History, first change EnableHistory of Scriptmanager to “true”. And then write the event onNavigate to Scriptmanager. The sample markup looks as below.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnableHistory="true"    OnNavigate="ScriptManager1_Navigate">

</asp:ScriptManager>

6.      In the code behind add the AjaxHistory in the GridView PageIndex Changed event

       protected void GridView1_PageIndexChanged(object sender, EventArgs e)

        {

            string pageIndex = (sender as GridView).PageIndex.ToString();

            ScriptManager1.AddHistoryPoint("paging", pageIndex);

         }

 

 On the ScriptManager Navigate Event, restore the history point added and show the concerned page when clicked on the browser history buttons    

   protected void ScriptManager1_Navigate(object sender, HistoryEventArgs e)

        {

            if (e.State.Count <= 0)

            {

                GridView1.PageIndex = 0;

                return;

            }

            string PageKey = e.State.AllKeys[0];

            string pageIndex = String.Empty;

            if (PageKey == "paging")

            {

                pageIndex = e.State[PageKey];

                int iPageIndex = Convert.ToInt32(pageIndex);

                GridView1.PageIndex = iPageIndex;

            }

            GridView1.DataSource = GetDataSet();

            GridView1.DataBind();

        }

 

7.      Now run the application and check the output the browser back/forward buttons are enabled even for asynchronous postbacks. Check the screenshot below after implementing Ajax history.

           Enabling Back button using Ajax History in ASP.Net AJAX 

We can also add Ajax HistoryPoints using client side framework of scriptmanager too without using the server side utilities. Let’s say user has another requirement like user can enter a student name on a textbox and when a button is clicked, all the student details are fetched from server using Pagemethods/webservices. Here are the steps to achieve the functionality and implement Ajax history.




1.      First drag the Scriptmanager to the page and Enable the History and PageMethods

Eg:

<asp:ScriptManager ID="ScriptManager1" runat="server" 

     EnablePageMethods="True" EnableHistory="true">

</asp:ScriptManager>

2.      Next take TextBox control for entering input and a Button control to fetch the results from server using Pagemethods and labels and TextBoxes to display the result. The entire markup looks as below:

          <table>

      <tr>

       <td colspan="2">                          

           <asp:TextBox ID="txtStudentName" runat="server"></asp:TextBox>

           <asp:Button ID="Button1" runat="server" Text="GetSutdentDetails"

               Width="117px" OnClientClick="return fnButtonClick() " />

       </td>

      </tr>

      <tr>

         <td>

          <asp:Label ID="Label1" runat="server" Text="StudentId"></asp:Label>

         </td>

         <td>

         <asp:TextBox ID="txtStudentId" runat="server"></asp:TextBox>    

         </td>

      </tr>

      <tr>

         <td>

          <asp:Label ID="Label2" runat="server" Text="Department"></asp:Label>

         </td>

         <td>

  <asp:TextBox ID="txtDepartment" runat="server" style="margin-bottom: 0px"></asp:TextBox>

         </td>

      </tr>

      <tr>

         <td>

          <asp:Label ID="Label3" runat="server" Text="University"></asp:Label>

         </td>

         <td>

         <asp:TextBox ID="txtUniverisity" runat="server"></asp:TextBox>

         </td>

      </tr>

     </table>

3.      Add the WebMethod on the server code which fetches the student details based on the student name. This is the sample method where the records are hard coded.

        [System.Web.Services.WebMethod]

        public static string[] GetStudentDetails(string studentname)

        {

            switch (studentname)

            {

                case "suresh":

   return new string[] { "S001", "Computer Science", "JNTU" };

                case "sravan":

                    return new string[] { "S002", "Electronics", "FDU" };

                case "satheesh":

                    return new string[] { "S003", "Electrical", "NUS" };

                case "sreekanth":

 return new string[] { "S004", "Mechanical", "Lousiana Tech" };                   

                default:

                    return null;

                   

            }

        }

4.      Now on the client side add the Navigate event during initialization. The code looks as below

    function pageLoad(sender, args)

    {

        Sys.Application.add_navigate(onNavigate);

    }

5.      When the GetStudentDetails button is click call the server method and assign callback method which displays the results

      var isNavigated = true;

    function getstudentdetails(studentname)

    {

      PageMethods.GetStudentDetails(studentname,onSucceed, onError);

      isNavigated = false;      

      Sys.Application.addHistoryPoint({stName: studentname},"Students");

      isNavigated = true;

      return false;

    }

    function fnButtonClick()

    {

      var studentName = document.getElementById("txtStudentName").value;

      getstudentdetails(studentName);

      return false;   

    }

      

    function onSucceed(result)

    {

      document.getElementById("txtStudentId").value = result[0];

      document.getElementById("txtDepartment").value = result[1];

      document.getElementById("txtUniverisity").value = result[2];     

    }

    function onError(result)

    {     

        alert(“Error Occurred”);

    }  

Note: Here onSucceed and OnError are call back methods to display the result.

6.      Nov add the OnNavigate event to display the results when clicked on the browser back/forward buttons

         function onNavigate(sender, e) 

     {   

      var studentname = e.get_state().stName;

      if(isNavigated)

      RestoreStudentDetails(studentname);

     }

   

    function RestoreStudentDetails(studentname)

    {

     if (studentname != undefined)         

      getstudentdetails(studentname);    

 }

7.      Now run the application and check the output. Check the screenshot below.

              Enabling Back button using Ajax History in ASP.Net AJAX

 

This is how we can implement the Ajax history using the client side framework of Scriptmanager.

If you have observed the screenshot of Ajax history, the url is changed and encrypted for security purpose. We can also disable this by using EnableSecureHistoryState of the Scriptmanager

Eg: EnableSecureHistoryState = “False”

  <asp:ScriptManager ID="ScriptManager1" runat="server" EnableHistory="true"

        OnNavigate="ScriptManager1_Navigate" EnableSecureHistoryState="False">

We can also assign the page title when we are adding ajax history points. Just use Page.Tittle = “Some title” in the server code before you are adding the AjaxHistory point.

References

1.      http://www.asp.net/aspnet-in-net-35-sp1/videos/
introduction-to-aspnet-ajax-history

2.      http://dotnetslackers.com/articles/aspnet/
AFirstLookAtASPNETExtensions35HistoryPoints.aspx

3.      http://dotnetslackers.com/articles/ajax/
ClientHistoryPointsInASPNET35Extensions.aspx

Conclusion

In this article I have demonstrated how to add Ajax HistoryPoints when we use Asp.Net 3.5 Ajax for asynchronous postbacks and updates. This sort of maintaining Ajax history is mainly used in wizard kind of functionalities viz adding a new payee in the banking web applications and perform business transaction or filling the details of consumer and etc. In future I will come up with an article how it works internally. Happy Reading!!

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Request Complete Code
Hi,

Is it possible for you to send me the complete code to amirhb@gmail.com ?

Tnx!