开发者

problem with window scrolling with asp.net button control

In web application, i tried scrolling the window vertically by increasing a y axis height to 500 with a javascript that is attached to OnClientClick event of a asp.net button control with id Button1.

The script i have used is

<script language="JavaScript">

function scrollToWindow()
{
  window.scrollTo(0,500);
}

</script&g开发者_运维技巧t;

and the button code is as follows

<asp:Button ID="Button1" runat="server" 
Text="Scroll to bottom" OnClientClick="scrollToWindow()" />

If i run this page and click that button, the page scroll is not working properly. when i put alert inside that script and debug, i found that the page is actually scrolling to 0,500 but again its rendering to its normal position because of some reasons. could someone help to overcome this issue and let me know the reason behind that??


Yours page is reloaded with default settings after you click on the button ( postback). OnClientClick does not prevent it unless you block postback in javascript code ( return false; at the end).


The reason it resets is that an asp button does a submit on the page. So first it does the javascript onclick, and then postback to the server, which causes a page refresh.

Solution 1:

In the page directive on top of your aspx file, you can add a setting to maintain the scroll position:

<%@ Page  MaintainScrollPositionOnPostback="True" %>

In this case you can define your button as you did originally:

<asp:Button ID="Button1" runat="server" 
 Text="Scroll to bottom" OnClientClick="scrollToWindow()" />

Note: this setting does not work in Safari and Google Chrome, but it works in other major browsers (IE5+, Firefox, Opera).

Solution 2:

To make it work also with Safari and Google Chrome, you can instead implement AJAX to prevent full page refresh.

 <asp:ScriptManager runat="server" ID="ScriptManager1" />
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
    <asp:Button runat="server" ID="Button1" Text="Button"
     onclick="Button1_Click" OnClientClick="alert('hello');" />
    </ContentTemplate>
    </asp:UpdatePanel>

Just make sure that all GUI that changes as a result of the button click needs to be part of the same <asp:UpdatePanel> that is triggered by the button click.


The entire page is likely posting back due to the fact that it is a button you have placed on the page. Clicking it will, in essence, "refresh" the page, which leads to the result you're seeing. Running window.scrollTo() like you desire is better suited for a link or something. You can run JavaScript inside an asp:HyperLink like this, or just use a standard HTML anchor tag to get the job done.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜