** 用实例学:ASP.NET的include的用法 **
( 2004-11-13 )
** 引言: ** ** **
我们学过的 Code 分离到不同文件的方法,主要包括:
_ 程序集 .dll _ 、 _
1<inherits src="">.cs _ 、 _ <script src="">.cs _ 、 _用户控件_ _ .ascx _ 、 _ include _ 、 _ Response.WriteFile() _
2
3程序集 .dll :这是最高级的方法,它引用的是一个被编译为 IL 的 DLL (程序集)文件。
4
5<inherits src>.cs :用这种方法,可以先定义一个继承 Page 类的新类,再在 ASPX/ASCX 文件中加工此类。
6
7<script src>.cs :可以把 <script runat=”server”> 部分分离到一个新文件。
8
9用户控件 .ascx :把一段 ASP.NET 代码作为一个控件引入。
10
11include :这是今天的主题,详见下。
12
13Response.WriteFile() :他只能用于引入一段“纯客户端代码( DHTML )”,扩展名可随意。
14
15
16** 实验项目描述:
17** ** **
18
19
20
21
22我想没有什么比一个 UI 更说明问题了,那么这是一个什么页面呢?
23
24这是一个典型的“上中下”结构的网页,在实作中:“页头 / 页脚”可能是不变的,而中部可能是变化的。
25
26于是在实作中,如果用“ include 法”我们需要把三个部分离出来,单为一个文件。
27
28之后,可以使用一个“主文件”,分别把它们三个文件 include 进来。
29
30而今天,我们只是一个实验,所以我们是这样设计的:
31
32中部为一个“主文件”,之后把上下两部分 include 进来。
33
34最后,我们还会把一些关键技术进行总结。
35
36** 代码实现: ** ** **
37
38【上部分文件: head.aspx 】
39
40
41
42
43<script runat=server>
44
45void click1 (object a,EventArgs b)
46
47{ label1.Text=text1.Text;
48
49label2.Text=text2.Text;}
50
51</script>
52<h1>The Softzz's New page</h1>
53<p>2004-11-15</p>
54
55Name:<asp:textbox id="text1" runat="server"></asp:textbox>
56
57
58
59Pass:<asp:textbox id="text2" runat="server" textmode="password"></asp:textbox>
60
61
62
63<asp:button id="button1" onclick="click1" runat="server" text="ClickMe"></asp:button>
64<hr size="1" width="80%"/>
65
66
67
68
69【上部分文件: end.a 】
70
71
72
73
74<script runat="server">
75
76void click2 (object a,EventArgs b)
77
78{ label1.Text=text3.Text;
79
80label2.Text=text4.Text;
81
82}
83
84</script>
85<hr size="1" width="80%"/>
86
87Name:<asp:textbox id="text3" runat="server"></asp:textbox>
88
89
90
91Pass:<asp:textbox id="text4" runat="server" textmode="password"></asp:textbox>
92
93
94
95<asp:button id="button2" onclick="click2" runat="server" text="ClickMe"></asp:button>
96<h5>```
97= DateTime.Now.ToString()
98```</h5>
99<b><p>CopyRight: SoftZZ</p></b>
100
101
102
103
104【主文件: index.aspx 】
@ Page Language=C#
1
2<center>
3<form runat="server">
4<!-- #include file="head.aspx" -->
5<p>This is a new test page.Please look at the info:</p>
6
7
8
9
10
11User's Name: <b><asp:label id="label1" runat="server/"></asp:label></b>
12
13
14
15
16
17User's Pass: <b><asp:label id="label2" runat="server/"></asp:label></b>
18<!-- #include file="end.a" -->
19</form>
20</center>
21
22** 关键技术·记述: **
23
24上面的例子还能说明什么呢?
25
26l include 可以把几个文件最终拼成一个文件,而作为元素的每一页,只是最后拼成的最终页的片段。
27
28l 被拼的页、最终的页,均为 ASP.NET 代码容器,而非 HTML 文本。
29
30l 拼页时,是按顺序的。
31
32l 这些文件中的代码,在被拼时,只是普通文字,当最终拼成后,才会被检查 / 编译 / 报错 / 显示……
33
34l 一个文件中可以多次 include 另一个文件。但前提是不能使“声明 / 定义” ( 标识符 ) 部分重复 ( 重名 ) 。
35
36l 如果在各文件中终有“ runat=server ”的控件,一定要注意 <form runat="”server”"> 的始 / 终位置。
37
38l 一页中只能有一个 <form runat="”server”"> ,就算可以设置 form 的 id 也不能有多个。
39
40l 一页中可能多次出现 <script runat="”server”"></script></form></form></inherits>