在Visual studio 2015中可以通过Add-->New Item,添加Web Forms Server Control,自动生成的代码如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication23 { [DefaultProperty("Text")] [ToolboxData("<{0}:WebCustomControl1 runat=server></{0}:WebCustomControl1>")] public class WebCustomControl1 : WebControl { [Bindable(true)] [Category("Appearance")] [DefaultValue("")] [Localizable(true)] public string Text { get { String s = (String)ViewState["Text"]; return ((s == null) ? String.Empty : s); } set { ViewState["Text"] = value; } } protected override void RenderContents(HtmlTextWriter output) { output.Write(Text); } } }
在Web Page(即在aspx文件)中引用该Server Control,代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication23.WebForm1" %> <%@ Register Assembly="WebApplication23" Namespace="WebApplication23" TagPrefix="ccl" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <ccl:WebCustomControl1 ID="ServerControl1" runat="server" Text="daniel_test" /> </div> </form> </body> </html>
在使用Register引用该Server Control后,在ToolBox中就会出现该自定义的服务器控件,如图:
参考链接:
http://www.beansoftware.com/ASP.NET-Tutorials/Custom-Server-Controls.aspx