1

I was just trying to learn some Asp.net Ajax stuff and calling javascript from my C# script.

I have a timer that triggers a method that calls a super simple javascript alert function. It also updates the time every 10 seconds. Now it looks like my code should work. There are no build errors, no exceptions just it doesn't work. The C# part that updates the time. The javascript does not make the alert.

    <%@ Page Language="C#" %>

    <!DOCTYPE html>
    <html>

    <head runat="server">
        <title></title>
        <script runat="server">
        protected void Page_load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Label1.Text = DateTime.Now.ToString();
            }
        }
        protected void Timer1_Tick(object sender, EventArgs e)
        {
            const string someScript = "alertMe";
            Label1.Text = DateTime.Now.ToString();
            ClientScript.RegisterStartupScript(this.GetType(),someScript, "alert('I was called from Content page!')", true);
        }
    </script>

    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:ScriptManager runat="server"> </asp:ScriptManager>
     <asp:UpdatePanel runat="server">
         <ContentTemplate>
             <asp:Label runat="server" ID="Label1"></asp:Label>
             <asp:Timer ID="Timer1" runat="server" Interval="10000" OnTick ="Timer1_Tick"></asp:Timer>
         </ContentTemplate>
     </asp:UpdatePanel>
        </div>
        </form>
    </body>
    </html>
4

2 回答 2

2

当您将触发回发的元素放入 UpdatePanel 时,您需要使用 ScriptManager 而不是 ClientScript。

将您的代码更改为:

ScriptManager.RegisterStartupScript(this,this.GetType(), someScript, @"alert('I was called from Content page!');", true);
于 2013-07-11T20:51:04.517 回答
0

你忘了一个;

ClientScript.RegisterStartupScript(this.GetType(),someScript, "alert('I was called from Content page!');", true);

大多数浏览器都有某种类型的错误控制台,您可以在这些问题发生时看到它们。

于 2013-07-11T20:54:53.280 回答