您的位置:首页 > 编程语言 > ASP

ASP.NET Web用户控件

2018-04-10 17:22 381 查看

用户控件可用来实现页面中可重用的代码,是可以一次编写就多处方便使用的功能块。它们是 ASP.NET控件封装最简单的形式。由于它们最简单,因此创建和使用它们也是最简单的。用户控件实际上是把已有的服务器控件组合到一个容器控件中,这样就可以创建出能在整个Web项目中使用的功能强大的对象了。

 简单来说,用户控件是能够在其中放置标记和Web服务器控件的容器,可以被看作个独立的单元,拥有自己的属性和方法,并可被放入到ASPX页面上。其工作原理与 ASP. NET页面非常相似。也可以这样理解:当一个Web窗体被当作 Server控件使用时这个Web窗体便是用户控件。下面给出搜索框用户控件的小例子:

一、添加用户Web控件 WebUserControl.ascx

 



二、WebUserControl.ascx    源码

一个textbox,三个button实现搜索功能
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl.ascx.cs"Inherits="用户Web控件.WebUserControl" %>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="baidu" runat="server" Text="百度搜索" OnClick="baidu_Click" />
<asp:Button ID="sougou" runat="server" Text="搜狗搜索" OnClick="sougou_Click" />
<asp:Button ID="sanliuling" runat="server" Text="360搜索" OnClick="sanliuling_Click" />

三、WebUserControl.ascx.cs后台源码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace 用户Web控件
{
public partial class WebUserControl : System.Web.UI.UserControl
{

protected void Page_Load(object sender, EventArgs e)
{

}

protected void baidu_Click(object sender, EventArgs e)
{
//获取textbox内容
string txt = TextBox1.Text;
//跳转网页
Response.Redirect("https://www.baidu.com/s?ie=utf-8&wd=" + txt);
}

protected void sougou_Click(object sender, EventArgs e)
{
//获取textbox内容
string txt = TextBox1.Text;
//跳转网页
Response.Redirect("https://www.sogou.com/web?query=" + txt);
}

protected void sanliuling_Click(object sender, EventArgs e)
{
//获取textbox内容
string txt = TextBox1.Text;
//跳转网页
Response.Redirect("https://www.so.com/s?ie=utf-8&q=" + txt);
}
}
}
到这里用户控件已经创建成功了!

四、可以放到任何网页使用了

直接把WebUserControl.ascx拉到*.aspx就可以直接使用了而且还有功能哦!
Search.aspx顶部会生成一句代码<%@ Register src="WebUserControl.ascx" tagname="WebUserControl" tagprefix="uc1" %>
下图已经把对应关系画了出来



五、在浏览器中查看,大功告成!



点击搜索就可以啦



WebUserControl.ascx可以在任意的*.aspx使用!

源码下载:点击下载  密码: rpqy
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ASP.NET 马春海