在使用LoadControl的方式,動態載入使用者控制項後,出現一個問題:當使用者控制項中的內容較多的時候(特別是伺服器控制項),頁面會出現一個Scroll,當啟用某一控制項時,頁面重新整理,此時,視窗的焦點將不在剛才啟用的控制項上。
這個問題在網上有很多的方式來解決,最簡單的一種方式: 添加智能導航,如在代碼中添加這樣的語句:
void Page_Load(Object sender, EventArgs e)
{
this.SmartNavigation = true;
}
使用這種方式雖然可能解決這個問題,但將帶來其它的問題。 特別是在使用動態載入控制項的時候。例如:
Redirect(url1); 1
DoSomething();
Redirect(url2); 2
LoadControl(control1);
AddControl(control1); 3
DoSomething();
control.Visual=false;
LoadControl(control2);
AddControl(control2); 4
此時如果選擇“後退”,IE將 link到 1的狀態,而不是 狀態 3。 也就是說使用智能導航的時候,所有載入動態網頁面的過程都當成一個網頁。
在CSDN中發現了一個比較好的方法(http://community.csdn.net/Expert/topic/2779/2779374.xml?temp=.850094)
1、在aspx頁面給body添加id屬性:<body id="thebody" MS_POSITIONING="GridLayout">
2、後台代碼(.cs檔案)中引用:using System.Text;
3、添加方法:
#region "防止頁面滾動"
private void RetainScrollPosition()
{
StringBuilder saveScrollPosition = new StringBuilder ();
StringBuilder setScrollPosition = new StringBuilder ();
RegisterHiddenField("__SCROLLPOS", "0");
saveScrollPosition.Append("<script language='javascript'>");
saveScrollPosition.Append("function saveScrollPosition() {");
saveScrollPosition.Append(" document.forms[0].__SCROLLPOS.value = thebody.scrollTop;");
saveScrollPosition.Append("}");
saveScrollPosition.Append("thebody.onscroll=saveScrollPosition;");
saveScrollPosition.Append("</script>");
RegisterStartupScript("saveScroll", saveScrollPosition.ToString());
if (Page.IsPostBack)
{
setScrollPosition.Append("<script language='javascript'>");
setScrollPosition.Append("function setScrollPosition() {");
setScrollPosition.Append(" thebody.scrollTop = " + Request["__SCROLLPOS"] + ";");
setScrollPosition.Append("}");
setScrollPosition.Append("thebody.onload=setScrollPosition;");
setScrollPosition.Append("</script>");
RegisterStartupScript("setScroll", setScrollPosition.ToString());
}
}
#endregion
4、在page_load中調用此方法:
this.RetainScrollPosition();