国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

[ASP.NET開發(fā)系列]在用戶控件中添加屬性

2024-07-10 13:12:12
字體:
供稿:網(wǎng)友

在中經(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>


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 塔城市| 寻乌县| 娱乐| 酒泉市| 花莲市| 崇阳县| 荃湾区| 当涂县| 安顺市| 化德县| 新民市| 泗水县| 中江县| 南昌县| 灵丘县| 家居| 辽源市| 罗定市| 赤峰市| 姚安县| 交城县| 镇赉县| 蚌埠市| 贵州省| 博野县| 新民市| 库车县| 深水埗区| 搜索| 丽江市| 安陆市| 从化市| 高要市| 翼城县| 抚顺市| 常熟市| 桑植县| 台江县| 班玛县| 鲜城| 龙川县|