在中經(jīng)常有一些代碼是在很多地方重復出現(xiàn)的,象導航欄、用戶登錄/注冊和首頁上面的一些固定欄目等。這些可重用的代碼我們可以把它寫成一個通用模塊供需要的地方來引用,這樣做即節(jié)省了開發(fā)時間還方便以后的維護。
在asp.net的web編程中提供了一種叫做“用戶控件”可以幫助我們完成這種做法,其文件擴展名是“.ascx”,由于ascx文件是用來插入aspx頁面中使用的,而一個aspx窗體只能包含一個<form>標志,所以ascx用戶控件不能包含<form></form>標志。
下面使用一個經(jīng)典入門范例來創(chuàng)建一個簡單的用戶控件,文件名為hello.ascx:
<html>
<body>
<h1>經(jīng)典入門范例</h1>
<hr>
<h3>hello word</h3>
</body>
</html>
把這段代碼保存為hello.ascx文件,然后在aspx頁面上調(diào)用,具體調(diào)用如下:
hello.aspx
<%@register tagprefix=”wen” tagname=”hello” src=”hello.ascx”%>
<html>
<body>
<form id=frm runat=server>
<wen:hello id=myhello runat=server>
</form>
</body>
</html>
在ie瀏覽器的地址里輸入 http://localhost/hello.aspx運行,將在頁面上打印出字符串“hello word”。
代碼說明:1)指令@register定義了用戶控件文件的標簽名“hello”和標簽前綴名”wen”;
2)src屬性是連接到用戶控件的相關的文件名;
3)<wen:hello id=myhello runat=server>這一句是在aspx窗體中調(diào)用用戶控件hello.ascx的語句。
以上的演示代碼沒有給控件添加屬性,下面我們舉一個用戶登錄的文件,把它寫成用戶控件,在向其中添加username和password這兩個屬性。向用戶控件添加屬性很簡單,只要在ascx文件中的<script></script>塊中定義就行了。
userlogin.ascx
<html>
<title>用戶登錄</title>
<body>
<table>
<tr>
<td>用戶名:</td>
<td><asp:textbox id=”txt1” runat=”server”></td>
</tr>
<tr>
<td>密 碼:</td>
<td><asp:textbox id=”txt2” textmode=”password” runat=”server”></td>
</tr>
<hr>
<tr>
<td></td>
<td><asp:linkbutton text=”登陸” runat=”server”></td>
</tr>
</table>
</body>
</html>
<script language=”c#” runat=”server”>
public string username{
get{return txt1.text;}
set{txt1.text=value;}
}
public string password{
get{return txt2.text;}
set{txt2.text=value;}
}
</script>
至此,我們已經(jīng)給userlogin.ascx文件添加了username和password這兩個屬性了,以下demo演示如何在aspx頁面上引用這兩個屬性。
userlogin.aspx
<%@register tagprefix=”wen” tagname=”userlogincontorl” src=” userlogin.ascx” %>
<html>
<title>引用屬性</title>
<body>
<form runat=”server”>
<wen: userlogin.ascx id=”mylogin” runat=”server”>
</form>
用戶名:<asp:label id=”lab1” runat=”server”><br>
密 碼:<asp:label id=”lab2” runat=”server”><br>
</body>
</html>
<script language=”c#” runat=”server”>
void page_load(object sender,eventargs e){
if(ispostback){
lab1.text=mylogin.username;
lab2.text=mylogin.password;
}
}
</script>
新聞熱點
疑難解答
圖片精選