简体   繁体   English

ASP.NET:RegisterStartupScript不起作用

[英]ASP.NET: RegisterStartupScript does not work

I'm trying to run a client-side script from the server-side on Page_Load , I found this code from here . 我正在尝试从服务器端在Page_Load上运行客户端脚本,我从这里找到了这段代码。 It's server side code: 它是服务器端代码:

protected void Page_Load(object sender, EventArgs e)
{
    if (!ClientScript.IsStartupScriptRegistered("alert"))
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(),
            "alert", "alertMe();", true);
    }
}

And it's client side code: 它是客户端代码:

<script type="text/javascript">
    function alertMe() {
        alert('Hello');
    }
</script>

But nothing happens on Page_Load . 但是Page_Load上没有任何反应。

UPDATE : source code coderun . 更新 :源代码运行

You are calling your alertMe() before it is defined, at the end of the page. 在页面末尾,您正在定义前的alertMe()调用。

All scripts registered with asp.net are rendered in the form tag. 在asp.net注册的所有脚本都在form标签中呈现。

I suggest moving your javascript block to the head of the page. 我建议将您的JavaScript块移到页面顶部。

<head runat="server">
  <script type="text/javascript">
    function alertMe() {
      alert('Hello');
    }
  </script>
</head>

Here is your modified code run that works as you expect. 这是修改后的代码 ,可以按预期运行

I suggest you to check two things 我建议你检查两件事

  1. Is your js function is not in some other function. 是您的js函数不在其他函数中。 Then it is not visible for server 然后对服务器不可见

  2. Is html tag which contain your script has runat="server" tag. 是包含您的脚本的html标签具有runat="server"标签。

In your case: 在您的情况下:

<head runat="server">
    <script type="text/javascript">
        function alertMe() {
            alert('Hello');
        }
    </script>
</head>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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