『 天道酬勤 』 李天平的博客


君子之行,静以修身,俭以养德。非淡泊无以明志,非宁静无以致远。
posts - 127, comments - 2851, trackbacks - 83, articles - 18
  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理

UpdatePanel中调用JS代码

Posted on 2011-11-10 14:46 李天平 阅读(631) 评论(0) 编辑 收藏

     页面中加入了UpdatePanel后,Response.Write("<script>function dis (){alert('这是调用写在server的JS');}</script>")来调用客户端脚本,无任何提示的无反应。如何在UpdatePanel中调用JS客户端脚本呢?
     方法:采用 ScriptManager.RegisterStartupScript(Control controlId,Type this.GetType(),String key,String script block)方法。

      有人说controlId必须是UpdatePanel里的,其实不然,page控件就可以。


     下面给出一个具体的实例:  

.cs部分
protected void Page_Load(object sender, EventArgs e)
     {
         ScriptManager.RegisterStartupScript(BtnJs,
this.GetType(), "alert", "<script>function


        dis (){alert(
'这是调用写在server的JS,如用Response.Write()是不能实现此效果的!!!      ');}</script>", false);
    
aspx部分
  <asp:ScriptManager ID="ScriptManager1" runat="server"   EnablePartialRendering="true" >      
         
        
</asp:ScriptManager>

        
<input id="BtnJs" type="button" value="CallServerJs" onclick="dis()" runat="server"/>
        
<asp:UpdatePanel ID="UpdatePanel1" runat="server"   UpdateMode="Conditional"   RenderMode="Block">
            
<ContentTemplate>
               
<asp:Button ID="Button6" runat="server" Text="Button" OnClientClick="dis()"/>
            
</ContentTemplate>     
        
</asp:UpdatePanel>



注意:BtnJs是UpdatePanel外的按钮 同时Button6重用了服务端注册的脚本

    附带说一下,如果是在普通的aspx中希望在服务器端注册下客户端脚本,可以用
Page.ClientScript.RegisterStartupScript(this.GetType(), String Key,String Js block ,Bool   AddScriptTag),除了注意粗体字以外,其他操作同上。紫色部分不能包含,如写了的话,浏览时会将脚本部分自动注释掉!