今天 想DEMO 一下,使用 動態(tài)控件 來增加JavaScript 的功能
平常 在做 互動網(wǎng)頁時,JavaScript 跟ASP.NET 的互動 一定會 很頻繁
今天這個范例 一方面demo 如何動態(tài)增加JavaScript 在我門的控件上,
一方面也示范JavaScript 如何 跟ASP.NET 互動中一個很基本的方式,下面 這范例 還蠻有趣的,
因為不想寫太多程式碼,但是要做互動效果一般都是要兩個ASP.NET 程式 比較好,結果讓我想了一下才搞出來。
 
以下程式延續(xù) 上一篇,加上JavaScript 來另開一個網(wǎng)頁呼叫自己本身并傳遞input 控件所輸入的值,在重新設定button 所會觸發(fā)的JavaScript
讓其可以回傳input 的值到原網(wǎng)頁上。
 
簡言之,本程式一人釋二角,有遞回使用的味道在里面了,該程式也詮釋出一部份動態(tài)控件的精神和優(yōu)勢,也就是互動控制
,藉由外部使用者的設定、輸入等,來動態(tài)設定網(wǎng)頁的呈現(xiàn)與控制方式,這個在很多程式語言、網(wǎng)頁程式中都可看到類似精神,但ASP.NET 最吸引人的地方,
就是 可以用物件化的方式,來制作網(wǎng)頁。
 
下面程式只是作一簡單的示范,其中精神讀者可以仔細了解祥加運用
 
JS_Demo.aspx
 1 <%@ Page Language="C#" AutoEventWireup="True" %>
 2
 3    <script language="C#" runat=server>
 4     public void Page_Init(object sender, System.EventArgs e)
 5     {
 6         string val = Request.QueryString.Get("val");
 7           
 8         Label message = new Label();
 9         message.ID = "請輸入你要說的話";
10         sourceTag.Controls.Add(message);
11
12         TextBox input = new TextBox();
13         input.ID = "input";
14         input.Text = val;
15         sourceTag.Controls.Add(input);
16
17         Button btnSayHello = new Button();
18         btnSayHello.ID = "btnSayHello";
19         btnSayHello.Text = "SayHello";
20         if(val != "" && val != null)
21             btnSayHello.Attributes.Add("OnClick", "return SetValue(" + input.ClientID + ");");
22         else
23             btnSayHello.Attributes.Add("OnClick", "return GetOtherValue(" + input.ClientID + ");");
24         sourceTag.Controls.Add(btnSayHello);
25     }
26       
27     void SubmitBtn_Click(Object sender, EventArgs e)
28     {
29         TextBox input = (TextBox)sourceTag.FindControl("input");
30         LiteralControl lc;
31         lc = new LiteralControl("<H3>" + input.Text + "</H3>");
32         sourceTag.Controls.Add(lc);
33     }
34
35    </script>
36 <html>
37 <head>
38     <meta http-equiv="content-type" content="text/html; charset=utf-8" />
39 </head>
40 <body>
41  <script type = "text/javascript">
42      var myInput;
43      function GetOtherValue(ctrl) {
44          myInput = ctrl;
45          var hWnd = window.open("JS_Demo.aspx?val=" + ctrl.value, "_blank" );
46          if ((document.window != null) && (!hWnd.opener))
47              hWnd.opener = document.window;
48          return false;
49      }
50      function SetValue(ctrl) {
51          window.opener.myInput.value = "Re: " + ctrl.value;
52          return false;
53      }
54 </script>
55    <form runat="server">
56
57       <h3>動態(tài)增加控件JavaScript 篇 www.</h3>
58       
59       <p/>
60       <div id="sourceTag"  runat="server">
61       </div>
62       <p/>
63       一條小龍
64    </form>
65 </body>
66 </html>
 
 
 
~~~ 一條小龍(babydragoner) ~~~