ScriptManager.RegisterStartupScript()方法在ajax页面无效

来源:互联网 发布:场矩阵布列松陈 编辑:程序博客网 时间:2024/05/16 06:01

如果不用Ajax,cs中运行某段js代码方式可以是:
Page.ClientScript.RegisterStartupScript(Page.GetType(), "", "<script>window.open('default2.aspx')</script>");
如果页面中使用了Ajax ,则上述代码即使执行也无效果。应对这种情况我们通常采用:
ScriptManager.RegisterStartupScript(this.Button1, this.GetType(), "alertScript", "window.open('default2.aspx');", true);
其中第一个参数为要注册脚本的控件ID,试了一下,只要是本页面的就行。
第二个参数为注册脚本控件类型,是控件还是this的GetType()都可以,typeOf(string)也没问题.
第三个脚本函数的名字,随便起。
第四个是脚本内容。
第五个是标明是否再添加脚本标签,如果第四个参数里包含了<script></script>标签,此处则为false,否则为true。

注意:aspx代码是这样的

<div>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:TextBox runat="server" ID="TextBox2" >
            </asp:TextBox>
            <asp:Button runat="server" Text="Button" ID="Button1" nClick="Button1_Click" />
        </ContentTemplate>
       <Triggers>
            <asp:PostBackTrigger ControlID="Button1" />
         </Triggers>
        </asp:UpdatePanel>
    </div>

我在Button1_Click的事件里注册脚本,一定要加红色的部分,否则总是提示不能parse什么东西!

另外,js无法干涉cs代码。所以一旦脚本注册成功,js和cs代码会互不相干的各自运行。

原创粉丝点击