Maintaining browser history in ASP.NET AJAX

0 comments
When we usually work with ASP.NET AJAX, we feel the lack of history in the browser (browser back and forward button doesn't work) when we perform any asynchronous operation. Here is the discussion to show how to maintain the browser history while performing ASP.NET AJAX asynchronous postback operation.

This is done by setting a property and specifying an event in the ScriptManager control.
Browser history created using ScriptManager control

Let's create an ASP.NET AJAX page that maintain the browser history


Sample page looks like below where a text box in which, write the step number and click on "Go to Next" button.

My source code of the .aspx page looks like below.
<form id="form1" runat="server">
<p>Write the number of step 1 to 4, click button. Now see the browser history.</p>
<div>
<asp:ScriptManager runat="server" ID="SM1" EnableHistory="true" OnNavigate="SM_Navigating" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Write Step: " />
<asp:TextBox ID="txtBox1" runat="server" /><br />
<asp:Button ID="btnSubmit" runat="server" Text="Go to Next" OnClick="SubmitData" />
<p><asp:Label ID="lblResult" runat="server" /></p>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>

In order to maintain the browser history, we need to set EnableHistory property of ScriptManager to true and specify the hanlder on OnNavigateevent,  have specified the handler event name as "SM_Navigating" that fires when the end user try to navigate the page from browser history. On click on the "Go to Next",  have fired a server side method called SubmitData.
Now, let's see the code-behind of the above .aspx page

public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SubmitData(object sender, EventArgs e)
{
DoTheAjaxWork(txtBox1.Text);
}
private void DoTheAjaxWork(string step)
{
if (SM1.IsInAsyncPostBack && !SM1.IsNavigating)
{
// perform all your real work here and add the history point
SM1.AddHistoryPoint("historyPoint", step, "Step " + step);
}
else
{
txtBox1.Text = step;
this.Title = "Step " + step;
}
}
protected void SM_Navigating(object sender, HistoryEventArgs e)
{
string state = e.State["historyPoint"];
if (!string.IsNullOrEmpty(state))
{
DoTheAjaxWork(e.State["historyPoint"]);
}
}
}

READ MORE >>

0 comments: