Maintaining scroll position on postbacks with ASP.NET

by Matthias Broschk November 18, 2007 12:47

Although web applications have become more and more advanced over the last years there are still several issues that remind you that you basically deal with plain old html pages. One of those issues is the disturbing fact that when working with long web pages you always end up at the top left corner of the page after postbacks. It can be really a pain in the neck having to scroll back to where you were before.

One way to address this problem would be by using Ajax to avoid postbacks of the whole page, but since you probably neither want to nor can use this approach in all situations (needless to say that this would be a lot of extra work), I searched for an other way to maintain the scroll position on postbacks.

JavaScript and the Document Object Model (DOM) offer functions for getting and setting both the vertical and horizontal scroll position. In order to maintain them I decided to persist those values inside hidden fields (“SNScrollX” and “SNScrollY”), which are send to the application on postbacks.

function SPP_GetScroll() {
    var scrollPosX;
    var scrollPosY;
    
    if (typeof window.pageYOffset != 'undefined') {
        scrollPosX = window.pageXOffset;
        scrollPosY = window.pageYOffset;
    }
    else if (typeof document.compatMode != 'undefined' 
&& document.compatMode != 'BackCompat') {
        scrollPosX = document.documentElement.scrollLeft;
        scrollPosY = document.documentElement.scrollTop;
    }
    else if (typeof document.body != 'undefined') {
        scrollPosX = document.body.scrollLeft;
        scrollPosY = document.body.scrollTop;
    }

    document.all.SNScrollX.value = scrollPosX;
    document.all.SNScrollY.value = scrollPosY;
}


function SPP_SetScroll() {
    window.scrollTo(document.all.SNScrollX.value, document.all.SNScrollY.value);
}

Because the the current scrolling position can change any second it is necessary to constantly update it’s value (“SPP_GetScroll”). Whereas after each postback the scroll position has to be set only once (“SPP_Set_Scroll”).

function InitializeTimers() {
    setTimeout(SPP_SetScroll, 1);
    window.setInterval(SPP_GetScroll, 50);
}

InitializeTimers();

The most reusable way to do this with ASP.NET would be by creating a server control.

public int X
{
    get
    {
        if (this.ViewState["X"] == null)
            return 0;
        else
            return (int)this.ViewState["X"];
    }
    set
    {
        this.ViewState["X"] = value;
    }
}


public int Y
{
    get
    {
        if (this.ViewState["Y"] == null)
            return 0;
        else
            return (int)this.ViewState["Y"];
    }
    set
    {
        this.ViewState["Y"] = value;
    }
}


protected override void OnPreRender(EventArgs e)
{
    base.OnPreRender(e);

    if (this.Page.IsPostBack)
    {
        this.X = Int32.Parse(this.Page.Request.Form["SNScrollX"]);
        this.Y = Int32.Parse(this.Page.Request.Form["SNScrollY"]);
    }

    this.Page.ClientScript.RegisterHiddenField("SNScrollX", this.X.ToString());
    this.Page.ClientScript.RegisterHiddenField("SNScrollY", this.Y.ToString());

    this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), "WebControls.javascript.scrolling.js");
}

By using public properties “X” and “Y” the scroll position can be set manually. The JavaScript file will be embedded and used as a web resource therefore one additional line in the file “AssemblyInfo.cs” is required.

[assembly: System.Web.UI.WebResource("WebControls.javascript.scrolling.js", "text/javascript")]

Now this control ca be used in any ASP.NET page but simply adding it to the page. The full source code can be found here.

Tags: , ,

ASP.NET | JavaScript

Comments

5/10/2010 8:22:43 PM #

pingback

Pingback from condosencinitas.com

san diego car insurance

condosencinitas.com

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen | Modified by Mooglegiant

About the author

Matthias Broschk from Hamburg (Germany) wrote his first goto statements in QuickBasic at the age of fifteen, switched to Visual Studio (i.e. Visual Basic / Visual C++) at version 5.0 and has been an addict of .NET since its early beginnings. There have been many other languages and frameworks (Java, PHP, ... ), but none about which he has been as enthusiastic as .NET. These days you can find more information in blogs rather than anywhere else. Therefore he has decided to share his experiences and start yet another .NET blog.