Code snippet of the day: persist the scroll position of an ASP. NET page

Source: Internet
Author: User
Sometimes we need to persist the scroll position of a page after a post back and not reset to the top, in ASP. NET 2.0, you can use the smartnavigation feature. however, setting smartnavigation to true in the page directive of an ASP. NET page is known to cause some problems with the rendering of the page. microsoft has confirmed that defaultredirect does not work and has posted a KB article for it.

As an alternative, here is JavaScript code to create a hidden field on the page and taps into the onscroll and onload events of the page's body. the code shown here is in the page's load event handler in the code behind file.

/**/ /// <Summary>
///Persist scrollbar's position after a PostBack
/// </Summary>
Private   Void Persistscrollposition ()
{
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 = Document. Body. scrolltop; " );
Savescrollposition. append ( " } " );
Savescrollposition. append ( " Document. Body. onscroll = savescrollposition; " );
Savescrollposition. append ( " </SCRIPT> " );

Registerstartupscript ( " Savescroll " , Savescrollposition. tostring ());

If (Page. ispostback)
{
Setscrollposition. append ( " <Script language = 'javascript '> " );
Setscrollposition. append ( " Function setscrollposition (){ " );
Setscrollposition. append ( " Document. Body. scrolltop = "   + Request [ " _ Scrollpos " ] +   " ; " );
Setscrollposition. append ( " } " );
Setscrollposition. append ( " Document. Body. onload = setscrollposition; " );
Setscrollposition. append ( " </SCRIPT> " );

Registerstartupscript ( " Setscroll " , Setscrollposition. tostring ());
}
}

Hope this helps

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.