ASP.NET为用户控件添加属性

在ASP.NET的web编程中提供了一种叫做“用户控件”可以帮助我们完成这种做法,其文件扩展名是“.ascx”,由于ascx文件是用来插入ASPX页面中使用的,而一个ASPX窗体只能包含一个<form>标签,所以ascx用户控件不能包含<form></form>标签,但用户控件可以含有<html><body>标签。

在实际开发中,为传递数据,经常会为用户控件增加属性,下面我们举一个用户登录的文件,把它写成用户控件,在向其中添加UserName和PassWord这两个属性。

WebUserControl1.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="HuiYingWeb.WebUserControl1" %> <html> <title>用户登录</title> <body> <table> <tr> <td>用户名:</td> <td><asp:TextBox ID="txt1" runat="server"></asp:TextBox></td> </tr> <tr> <td>密 码:</td> <td><asp:TextBox ID="txt2" TextMode="password" runat="server"></asp:TextBox></td> </tr> <hr> <tr> <td></td> <td><asp:LinkButton Text="登陆" ID="lbtnLogon" runat="server"></asp:LinkButton></td> </tr> </table> </body> </html>

WebUserControl1.ascx.cs

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace HuiYingWeb { public partial class WebUserControl1 : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { } /// <summary> /// 增加用户名属性 /// </summary> public string UserName { get { return txt1.Text; } set { txt1.Text = value; } } /// <summary> /// 增加密码属性 /// </summary> public string PassWord { get { return txt2.Text; } set { txt2.Text = value; } } } }

至此,我们已经给UserLogin.ascx文件添加了UserName和PassWord这两个属性了,以下DEMO演示如何在ASPX页面上引用这两个属性。

WebForm2.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="HuiYingWeb.WebForm2" %> <%@ Register src="WebUserControl1.ascx" tagname="WebUserControl1" tagprefix="uc1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> </div> <uc1:WebUserControl1 ID="WebUserControl12" runat="server" PassWord="bbbb" UserName="aaaa" /> </form> </body> </html>

上面图中会发现,属性已经在属性面板里显示出来了,我们设置用户名为aaaa,密码bbbb。现在我们获得设置的属性。WebForm2.aspx.cs

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace HuiYingWeb { public partial class WebForm2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Response.Write(WebUserControl12.UserName+","+WebUserControl12.PassWord); } } }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值