AJAX History control - using with a GridView
The History control allows web applications to inject browser history checkpoints based on the state of a AJAX control. The History control can store the state of a single serializable object, or can take a Dictionary<string, object> pairing where the string is a key identifying the serialized object.
To begin implimentation, add a <asp:History /> control to the pageā¦.
<asp:History ID="HistoryManager" runat="server" OnNavigate="HistoryManager_Navigate"></asp:History>
Then add a asyncronous trigger to the related UpdatePanel:
<Triggers>
<asp:AsyncPostBackTrigger ControlID="HistoryManager" />
</Triggers>
Once the History control has been added to the page, in your code-behind, you need to insert checkpoints as well as handle the a postback created by the browser buttons, or OnNavigate.
First, insert checkpoints where they make sense. This usually occurs within a partial page postback, for example a LinkButton within your UpdatePanel. In the following example, the AddGridHistory function is called whenever I want to store a history checkpoint. The function stores the state of a GridView by serializing every parameter needed to grab the exact data of a history checkpoint.
private void AddGridHistory()
{
Dictionary<string, object> gridState = new Dictionary<string, object>();
gridState.Add("ProductID", this.ProductID);
gridState.Add("NewerThan", this.NewerThan);
gridState.Add("SearchText", this.SearchText);
gridState.Add("SortCriteria", this.SortCriteria);
gridState.Add("SortOrder", this.SortOrder);
gridState.Add("NumberofRowsToReturn", this.NumberofRowsToReturn);
HistoryManager.AddHistoryPoint(gridState);
}
Now all we need to do is handle the OnNavigate event, which occurs when the browser Forward and Back buttons are used. The event handler is referenced above in our <asp:History /> control. When called, the handler will assign that state's Parameters, before the app retrieves data and DataBinds the GridView. The handler looks like this:
public void HistoryManager_Navigate(object sender, Microsoft.Web.Preview.UI.Controls.HistoryEventArgs args)
{
if (args.State.ContainsKey("ProductID")) this.ProductID = (string)args.State["ProductID"];
if (args.State.ContainsKey("NewerThan")) this.NewerThan = (string)args.State["NewerThan"];
if (args.State.ContainsKey("SearchText")) this.SearchText = (string)args.State["SearchText"];
if (args.State.ContainsKey("SortCriteria")) this.SortCriteria = (SortCriteria)args.State["SortCriteria"];
if (args.State.ContainsKey("SortOrder")) this.SortOrder = (SortOrder)args.State["SortOrder"];
if (args.State.ContainsKey("NumberofRowsToReturn")) this.NumberofRowsToReturn = (string)args.State["NumberofRowsToReturn"];
RefreshGrid();
}