ASP.net Postback - Scroll to Specific Position

后端 未结 9 1071
天命终不由人
天命终不由人 2020-12-15 16:50

I have an ASP.net WebForms page that has a lot of content on the top of the screen. It has a link button that will post back to the page and show another section of the page

9条回答
  •  南笙
    南笙 (楼主)
    2020-12-15 17:28

    I've tried Matthieu Charbonnier answer, but it didn't work unless I've added

    " window.scrollTo = function () { };" 
    

    as it was suggested in http://gnidesign.blogspot.com.au/2011/06/how-to-maintain-page-scroll-on-postback.html

    I've created a helper method, that's working in Chrome,FireFox and IE

    public static void ScrollToControl( Page page, string clientId, bool alignToTop)
     {
         //NOTE: if there are more than one call on the page, first one will take preference
         //If we want that last will take  preference, change key from MethodBase.GetCurrentMethod().Name to anchorName
         //recommended in http://gnidesign.blogspot.com.au/2011/06/how-to-maintain-page-scroll-on-postback.html              
         String script = " window.scrollTo = function () { };" + Environment.NewLine;
         script += String.Format("document.getElementById('{0}').scrollIntoView({1});" , clientId, alignToTop.JSToString());
         page.ClientScript.RegisterStartupScript(TypeForClientScript(), MethodBase.GetCurrentMethod().Name, script, true );
         //return script;
     }
     public static string JSToString(this bool bValue)
     {
         return bValue.ToString().ToLower();
     }
    

    Use getElementById('{0}').scrollIntoView is simpler than location.hash , because you don't need to add extra anchor element.

    Parameter alignToTop is very convenient to specify do you want to show control at the top or bottom of the screen.

提交回复
热议问题