asp.net ajax计时器控制触发两次然后停止

时间:2012-07-18 01:02:12

标签: asp.net ajax vb.net timer controls

基本上我只是试图实现一个定时器控件,它将为我交换横幅,然后在更新面板中更新。然而,计时器只影响我的页面一次,并且似乎被触发两次(我在表单上放了一个标签,并且每次更新时都试图递增1,然后它跳到2然后停止)。

                   <asp:ContentPlaceHolder ID="cphHead" runat="server">


                    <asp:ScriptManager ID="ScriptManager1" runat="server">
                    </asp:ScriptManager>
                    <asp:Timer ID="Timer1" runat="server" Interval="6000" OnTick="Timer1_Tick">
                    </asp:Timer>
                    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
                        <Triggers>
                            <asp:AsyncPostBackTrigger ControlID="Timer1" />
                        </Triggers>
                        <ContentTemplate>
                            <asp:Image ID="Image1" runat="server" ImageUrl="~/images/banner_2.jpg" />

                            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                        </ContentTemplate>
                    </asp:UpdatePanel>


                </asp:ContentPlaceHolder>

后面有我的代码

Partial Class ASPTravel
    Inherits System.Web.UI.MasterPage

    Private intnum As Integer = 0
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load


    End Sub



    Protected Sub LoginStatus1_LoggingOut(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.LoginCancelEventArgs) Handles LoginStatus1.LoggingOut
        Session.Abandon()
    End Sub




    Protected Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick

            intnum = intnum + 1
            Label1.Text = CStr(intnum)
            ' If intnum = 0 Then
            '  Image1.ImageUrl = "~/images/banner_1.jpg"
            '  intnum = 1
            ' Else
            '  Image1.ImageUrl = "~/images/banner_2.jpg"
            'End If
            Dim n As Integer = New Random().Next(1, 2)
            Image1.ImageUrl = "~/images/banner_" + n.ToString() + ".jpg"



    End Sub
End Class

1 个答案:

答案 0 :(得分:1)

从您的代码中删除Handles Timer1.Tick,它将正常工作。我已经检查过了。 像这样。

 Protected Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs)

参考:http://forums.asp.net/t/1642896.aspx/1

也是用户viewstate而不是变量。变量在asp.net中的每个回发中初始化。因此,不要在变量Private intnum As Integer = 0中保存值,而是将其保存在像这样的View状态

ViewState["intnum"] = 0

并在您的计时器点击事件中。

ViewState["intnum"]= (int) ViewState["intnum"] + 1
Label1.Text = CStr(ViewState["intnum"])