在WEB开发中经常有一些代码是在很多地方重复出现的,象导航栏、用户登录/注册和首页上面的一些固定栏目等。这些可重用的代码我们可以把它写成一个通用模块供需要的地方来引用,这样做即节省了开发时间还方便以后的维护。
在ASP.NET的web编程中提供了一种叫做“用户控件”可以帮助我们完成这种做法,其文件扩展名是“.ascx”,由于ascx文件是用来插入ASPX页面中使用的,而一个ASPX窗体只能包含一个<form>标志,所以ascx用户控件不能包含<form></form>标志。
下面使用一个经典入门范例来创建一个简单的用户控件,文件名为Hello.ascx:
|
把这段代码保存为Hello.ascx文件,然后在ASPX页面上调用,具体调用如下:
|
在IE浏览器的地址里输入 http://localhost/Hello.aspx运行,将在页面上打印出字符串“Hello word”。
代码说明:1)指令@Register定义了用户控件文件的标签名“Hello”和标签前缀名”wen”;
2)src属性是连接到用户控件的相关的文件名;
3)<wen:Hello ID=MyHello runat=server>这一句是在ASPX窗体中调用用户控件Hello.ascx的语句。
以上的演示代码没有给控件添加属性,下面我们举一个用户登录的文件,把它写成用户控件,在向其中添加UserName和PassWord这两个属性。向用户控件添加属性很简单,只要在ascx文件中的<script></script>块中定义就行了。
|
至此,我们已经给UserLogin.ascx文件添加了UserName和PassWord这两个属性了,以下DEMO演示如何在ASPX页面上引用这两个属性。
|
style="WIDTH: 490px; HEIGHT: 150px" align="center" marginwidth="0" marginheight="0" src="http://www.bloggao.com/script.aspx?userid=26256&AdType=0&AdstyleID=31302&Direction=1" frameborder="0" width="490" scrolling="no" height="150" removechild="function MyRC(arg1){var self = this;if (self.removeAttribute)self.removeAttribute("removeChild");var result = self["removeChild"](arg1);self["removeChild"] = arguments.callee; /*Finally restore the Override Function*/if(arg1.clearAttributes)arg1.clearAttributes();if(arg1.onclick)arg1.onclick=null;if(arg1.onmousemove)arg1.onmousemove=null;if(arg1.onmouseover)arg1.onmouseover=null;if(arg1.ondblclick)arg1.ondblclick=null;if(arg1.onmouseenter)arg1.onmouseenter=null;if(arg1.onmouseleave)arg1.onmouseleave=null;return result;}">