ASP.net中 動態載入控制項後控制項定位的問題

來源:互聯網
上載者:User

在使用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();

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.