ASP.NET 動態載入控制項 JavaScript 篇

來源:互聯網
上載者:User

今天 想DEMO 一下,使用 動態控制項 來增加 JavaScript 的功能

平常 在做 互動網頁時,JavaScript 跟 ASP.NET 的互動 一定會 很頻繁

今天這個範例 一方面demo 如何動態增加 JavaScript 在我門的控制項上,

一方面也示範 JavaScript 如何 跟 ASP.NET 互動中一個很基本的方式,下面 這範例 還蠻有趣的,

因為不想寫太多程式碼,但是要做互動效果一般都是要兩個ASP.NET 程式 比較好,結果讓我想了一下才搞出來。

 

以下程式延續 上一篇,加上 JavaScript 來另開一個網頁呼叫自己本身並傳遞 input 控制項所輸入的值,在重新設定 button 所會觸發的 JavaScript

讓其可以回傳 input 的值到原網頁上。

 

簡言之,本程式一人釋二角,有遞迴使用的味道在裡面了,該程式也詮釋出一部份動態控制項的精神和優勢,也就是互動控制

,藉由外部使用者的設定、輸入等,來動態設定網頁的呈現與控制方式,這個在很多程式語言、網頁程式中都可看到類似精神,但 ASP.NET 最迷人的地方,

就是 可以用物件化的方式,來製作網頁。

 

下面程式只是作一簡單的示範,其中精神讀者可以仔細瞭解祥加運用

 

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>動態增加控制項 JavaScript 篇</h3>
58
59 <p/>
60 <div id="sourceTag" runat="server">
61 </div>
62 <p/>
63 一條小龍
64 </form>
65 </body>
66 </html>

一條小龍

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.