jorame
jorame

Reputation: 2207

How can I prevent a page from going to the top every time a button with OnClick event is clicked?

How can I prevent a page from going back to the top every time a button is click? I still want to execute the code on the "OnClick" event for the button.

Example:

Almost all of our forms have a button on the bottom of the page which are suppose to bring some data back from the DB and populate some labes and textboxes located on the bottom of the page, when the button is click it takes user back to the top of the page. How can I prevent this from happening?

Any help will be really appreciate it.

Upvotes: 2

Views: 3344

Answers (4)

Brian Garson
Brian Garson

Reputation: 1160

in your page declaration you can add MaintainScrollPositionOnPostback="true" ie:

<%@ Page Language="C#" ... MaintainScrollPositionOnPostback="true" %>

you can also put that in your web.config under system.web or declare it from codebehind Page.MaintainScrollPositionOnPostback=true;

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460158

There are two options:

  1. Use ASP.NET Ajax, in particular the UpdatePanel control
  2. Set MaintainScrollPositionOnPostback to true on page level or in web.config

Upvotes: 3

competent_tech
competent_tech

Reputation: 44931

Assuming the OnClick event is handled on the server and not in javascript, the easiest thing is wrap the controls to be updated in an UpdatePanel and have the update panel trigger on the button's click event.

Here is an example from Microsoft's documentation:

<asp:Button ID="Button1" 
            Text="Refresh Panel"
            runat="server" />
<asp:ScriptManager ID="ScriptManager1" 
                   runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" 
                 UpdateMode="Conditional"
                 runat="server">
                 <Triggers>
                   <asp:AsyncPostBackTrigger ControlID="Button1" />
                 </Triggers>
                 <ContentTemplate>
                 <fieldset>
                 <legend>UpdatePanel content</legend>
                 <%=DateTime.Now.ToString() %>
                 </fieldset>
                 </ContentTemplate>
</asp:UpdatePanel>

Upvotes: 4

kprobst
kprobst

Reputation: 16651

In the function handler for the button make sure you return false. You might be actually posting the page with those buttons rather than just doing something on the click event.

Upvotes: 0

Related Questions