我们知道当我们使用ASP.NET AJAX的一些方便的服务端控件如UpdatePanel,我们的浏览器不能保存这些异步浏览的页面状态,而ASP.NET3.5 Extensions给我们提供了一个解决方法,下面演示一下使用实例:
一:简单示例
1. 首先下载安装ASP.NET 3.5 Extensions
2.新建一个ASP.NET3.5 Extensions Web Application
3. 向页面拖动一个ASP.NET3.5 Extensions下的ScriptManger和UpdatePanel
4. 修改Default.aspx,注意黄色部分
EnableHistory默认是false,要设为true, EnablestateHash就是地址栏是否加密
5. 修改Default.aspx.cs
当我们需要保存信息时,添加一个历史点,保存供还原时使用的一些信息,然后当点击后退按钮时,会执行ScriptManager_Navigate来使用我们保存的信息。
6.效果
7.原理
我们看一下页面的源码,发现如果我们EnableHistory="true",会自动给我们页面添加一个Iframe,当我们后退,前进时这些还原点是更改Iframe.
二、分页示例:
1.修改页面Default.aspx如下:
2. 修改页面Default.aspx.cs如下:
我们添加一个List来提供数据源,完整代码如下:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
//Descirption: demo ajax history
//Created by: Jack Wang

namespace AjaxHistory


{
public partial class _Default : System.Web.UI.Page

{
private static string historyTime = "historyTime";
private List<Student> students = new List<Student>();
protected void Page_Load(object sender, EventArgs e)

{
for (int i = 0; i < 20; i++)

{

students.Add(new Student
{ Name = "TestName" + i.ToString(), Address = "Street" + i.ToString(), age = i });
}
if (!Page.IsPostBack)

{
this.GetData();
}
}
protected void mGetTimeButton_Click(object sender, EventArgs e)

{
this.mResultTimeLabel.Text = DateTime.Now.ToString();
ScriptManager.GetCurrent(this).AddHistoryPoint(historyTime, this.mResultTimeLabel.Text, DateTime.Now.Second.ToString());
}

protected void ScriptManager1_Navigate(object sender, HistoryEventArgs e)

{
//restore time label
if (!String.IsNullOrEmpty(e.State[historyTime]))

{
this.mResultTimeLabel.Text = e.State[historyTime].ToString();
}

//restore gridview result
if (!string.IsNullOrEmpty(e.State["gridviewResult"]))

{
GridView1.PageIndex = Int32.Parse(e.State["gridviewResult"]);
this.GetData();
}
}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)

{
GridView1.PageIndex = e.NewPageIndex;
//just need save page index for history
ScriptManager.GetCurrent(this).AddHistoryPoint("gridviewResult", e.NewPageIndex.ToString(), "gridviewResult"+e.NewPageIndex.ToString());
this.GetData();
}

public void GetData()

{
GridView1.DataSource = students;
GridView1.DataBind();
}
}

public class Student

{

public string Name
{ get; set; }

public int age
{ get; set; }

public string Address
{ get; set; }
}
}


3.效果:

本文示例代码下载:https://files.cnblogs.com/cnblogsfans/AjaxHistory.rar
我的这篇博客里写了使用ASP.NET 3.5
Extensions管理浏览器历史:使用客户端