简体   繁体   中英

Javascript wont work on Timer_Tick method on ASP.NET

I have a Timer that ticks every 2 seconds and gets the percent value that constantly changes, this works fine when it displays in a label. I want to the same thing but to display in a message box using javascript, this display fine for the first time but when the value changes the value in the alert pop up remains the same.

protected void TimerProgress_Tick(object sender, EventArgs e)
    {        
        percent = max_time.PercentGoalMetToday(i.ToString());  
        lbPercent.Text = percent; //WORKS
        JavaScriptMethod();
    }

    protected void JavaScriptMethod()
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("<script type = 'text/javascript'>");
        sb.Append("function main(){");
        sb.Append("alert('");
        sb.Append(percent);
        sb.Append("')};");
        sb.Append("var myVar = setInterval(function () { main() }, 4000);");
        sb.Append("</script>");
        ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
    }

ASPX

   <asp:UpdatePanel ID="UpdatePanelProgressBar" runat="server">
    <ContentTemplate>
             <asp:Label ID="lblPercent" runat="server" Text="" CssClass="Percent"></asp:Label>  
   </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="Timer" />
        </Triggers>
    </asp:UpdatePanel>
    <asp:Timer ID="Timer" Interval="2000" runat="server" OnTick="TimerProgress_Tick">
    </asp:Timer>

我将使用SignalR来实现这一点,SignalR旨在使您的服务器与浏览器高效且实时地交换数据。

我知道它可以工作,只需将ClientScript.RegisterClientScriptBlock更改为ScriptManager.RegisterStartupScript,它就会刷新。

ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "temp", sb.ToString(), false); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM