Marcel Vogel
Marcel Vogel

Reputation: 159

Set javascript ScrollTo after submit form with updatepanel and masterpages

I have a form with a submit function in a updatepanel.

To test it I use alert and this is working fine. I submit the form and the alert pops up. So the code is working.

protected void SendProfileForm_Click(object sender, EventArgs e)
{
    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), 
    "ScrollTo", "alert('test');", true);
}

Now I change it into this, and this does nothing.

protected void SendProfileForm_Click(object sender, EventArgs e)
{
    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), 
    "ScrollTo", "window.scrollTo(0, 500);", true);
}

if I do a onclientclick with this code window.scrollTo(0, 500); then it is working. So this javascript code is working.

What am I doing wrong.

Upvotes: 1

Views: 592

Answers (1)

Vitor Canova
Vitor Canova

Reputation: 3976

Since you are posting a asynchronous call you must use ScriptManager client API:

Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(MyScrollTo);

This will fire that function every time the page load. So you need to code some logic to this work:

var needScroll;

function MyScrollTo(){
     if(needScroll){
        window.scrollTo(0,500);
     }
}

So you server side code need to set needScroll variable:

ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), 
    "ScrollTo", "var needScroll = true;", true);

If you want more information about ScriptManager client API take a look here.

Upvotes: 1

Related Questions