书签功能失效的原因在于,Ajax尽量避免一个完整页面的刷新。状态改变,URL不会。唯一改变的是URL的hash值。
书签问题的解决办法:只要当前页面的状态发生改变,就将这个状态信息放到当前页的hash中。
当URL的hash值发生改变时,Mozilla浏览器会自动创建一个历史条目。
但Internet Explorer只会在一个HTTP请求被创建后才会创建一个历史条目。光改变URL的hash值不会发出这样的请求。
通过在页面上建一个iframe,设置css使iframe不可见。
ASP.NET 3.5 SP1 / VS 2008 SP1 的做法,直接引用已经内建在新版 ScriptManager 控件内的 History Navigation 功能,达成和上一篇文章相同的效果。
如 Dino Esposito 在这篇文章所说的:
http://dotnetslackers.com/articles/aspnet/AFirstLookAtASPNETExtensions35HistoryPoints.aspx
在已安装 VS 2008 SP1 的网站里 (等同已安装 .NET 3.5 SP1),先启用 ScriptManager 内建的 History Navigation 功能,并建立 ScriptManager1_Navigate 事件处理函数,如下:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnableHistory="true"
onnavigate="ScriptManager1_Navigate">
</asp:ScriptManager>
之后只要使用者在 URL 网址中做 Navigate 时 (如本帖下载示例中,在 UpdatePanel 中的 GridView 按页码换页后,再按浏览器的「上一页」时),就会触发此一事件。
ScriptManager..::.Navigate Event:
Occurs when the user clicks the browser's Back or Forward button.
接下来,程序员就要在 Code-Behind 中撰码,在适当时机加入 History Point。以本帖下载示例而言,就是在 GridView1_PageIndexChanged 事件处理函数中,撰码加入 History Point。此后,当使用者在做 URL Navigate 时,例如像本例中,单击 GridView 的页码换页时,新版的 ScriptManager 控件就会在 URL 网址后面,加上一串看似乱码的 user state。如本帖的前一篇文章所提过的,这串浏览器的 navigating 历程信息,会经过「序列化 (serialization)」并加密后,再附加在 URL 网址后方,以供浏览器作为辨识之用。
和传统的 AJAX + GridView 网页,有几个不同点:
1、当 GridView 换页时,IE (或 Firefox) 左上方的「上一页、下一页」按钮会自动启用;若为传统的 AJAX 网页则不会。
2、假设您换页到 GridView 的第二页 (或其它任何一页),此时若再进到别的页面,再按浏览器左上方的「上一页」回来时,GridView 仍会停在第二页;若为传统的 AJAX 网页则不然,而是一律跳回 GridView 的第一页。
3、当 GridView 换页后,此时若将该页加入浏览器的「书签 (bookmark)」,会一并记录是在 GridView 的哪一页;若为传统的 AJAX 网页则不会记录。
4、搭配 FormView、DetailsView 控件使用时,在改变这两个控件的状态时 (Insert、Edit、ReadOnly mode),亦能记录页数和 state (这点版工我未测试成功)。
5、搭配 ASP.NET 的 Wizard 控件使用时,亦能记录页数和 state (这是 Dino 讲的,这点版工我未试过)。
One problem faced by a typical AJAX application is that a partial page update is not added to the history of the Web browser. This means that the browser’s Back button does not move back one AJAX step, but moves back one entire document, which is unlikely to be what the user expects. The ASP.NET AJAX History control allows the developer to insert history points so that the user may click the browser’s Back and Forward buttons to move between AJAX steps.
Presented by Scott Golightly
Duration: 8 minutes, 59 seconds
Date: 1 June 2007
http://www.asp.net/learn/ajax-videos/video-149.aspx
[1] MSDN Library, 「ScriptManager.Navigate Event (System.Web.UI)」:
http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.navigate.aspx
[2] MSDN Library, 「ScriptManager..::.AddHistoryPoint Method 」:
http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.addhistorypoint.aspx
[3] Dino Esposito, 「A First Look at ASP.NET Extensions 3.5—History Points」:
http://dotnetslackers.com/articles/aspnet/AFirstLookAtASPNETExtensions35HistoryPoints.aspx