利用ASP.NET AJAX的ScriptManager來動態註冊Client端的javascript

利用ASP.NET AJAX的ScriptManager來動態註冊Client端的javascript

這篇主要是介紹如何利用asp.net ajax 的ScriptManager來動態註冊Client端的javascript

C#範例

Default.aspx

01 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
02
03 <%@ Register Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
04     Namespace="System.Web.UI" TagPrefix="asp" %>
05 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
06 <html xmlns="http://www.w3.org/1999/xhtml">
07 <head id="Head1" runat="server">
08     <title>Untitled Page</title>
09 </head>
10 <body>
11     <form id="form1" runat="server">
12         <asp:ScriptManager ID="ScriptManager1" runat="server" />
13         <div>
14             <asp:UpdatePanel ID="UpdatePanel1" runat="server">
15                 <ContentTemplate>
16                     <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
17                     <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
18                     <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
19                     <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"
20                         ErrorMessage="不可為空白"></asp:RequiredFieldValidator>
21                 </ContentTemplate>
22             </asp:UpdatePanel>
23         </div>
24     </form>
25 </body>
26 </html>
27


Default.aspx.cs

01 using System;
02 using System.Data;
03 using System.Configuration;
04 using System.Web;
05 using System.Web.Security;
06 using System.Web.UI;
07 using System.Web.UI.WebControls;
08 using System.Web.UI.WebControls.WebParts;
09 using System.Web.UI.HtmlControls;

10
11 public partial class _Default : System.Web.UI.Page
12 {
13     protected void Page_Load(object sender, EventArgs e)
14     {
15
16     }

17     protected void Button1_Click(object sender, EventArgs e)
18     {
19         this.Label1.Text = this.TextBox1.Text;
20         ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('" + this.TextBox1.Text + "');", true);
21     }

22 }