Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.net Postback - Scroll to Specific Position

People also ask

How to maintain scroll position on PostBack in mvc?

Your scroll position is always preserved upon postback because the @Html. HiddenFor fields store your current scroll and pass it to the model on post. And then, when the page comes up it gets the scrollTop value from the model. At the end your page would behave like webform, everything stays intact.

How do you scroll to the top in C#?

I do it for my asp.net c# project with javascript. When you are on top of your page, the button for "Scroll to Top" will be hidden. You can change the button style with another image/colors/position. If you face problem, you can comments here.


Page.MaintainScrollPositionOnPostBack = true; should take you back to the same position on the screen, but you could use AJAX, or you could use SetFocus() to focus on a specific control after the postback:

http://msdn.microsoft.com/en-us/library/ms178232.aspx


You can use the code below if you have an anchor for the location:

Page.ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#MOVEHERE';", true);

In your case I suggest you to keep the default value of Page.MaintainScrollPositionOnPostBack, and use the pure javascript scrolling function

function scrollToDiv()
{
    document.getElementById('yourDiv').scrollIntoView();
}

And call it at the page startup with a little delay of 1ms (pure javascript again)

setTimeout(scrollToDiv, 1);

And finally call it from the C# code behind, with the RegisterStartupScript (js executed after all the page has been loaded) :

ScriptManager.RegisterStartupScript(Page, typeof(Page), "ScrollToADiv", "setTimeout(scrollToDiv, 1);", true);

Like this, it will bypass any asp automatic scrolling


try this

protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack) {
            string targetId = Page.Request.Params.Get("__EVENTTARGET");
            Page.ClientScript.RegisterStartupScript(this.GetType(), "focusthis", "document.getElementById('" + targetId + "').focus()", true);

        }
    }