ASP.NET Custom Controls

后端 未结 4 2053
你的背包
你的背包 2021-01-15 04:56

How do you create a custom control (not an ASCX control) and, more importantly, use it in your project? I\'d prefer not to create a separate project for it or compile it as

4条回答
  •  灰色年华
    2021-01-15 05:06

    Server controls should be compiled into a DLL. There should be no reason to be afraid of having an additional assembly in your project, and it helps create good project organization.

    ASP.NET Server controls are actually custom classes in an assembly. They do not have an "ascx" markup file associated to them.

    To use a ASP.NET Server Control, you need to tell ASP.NET where to look for its class.

    First, create a Class Library project and add it to your solution, I'll call mine "CustomControls.dll".

    Once there, add a simple class to be your webcontrol:

    public class Hello : System.Web.UI.WebControl
    {
        public override Render(HtmlTextWriter writer)
        {
            writer.Write("Hello World");
            base.Render(writer);
        }
    }
    

    Build your project, and add it as a reference to your main web project.

    Now, in the ASPX page that you want to use this control, you need to register it, so add this as the first line in the aspx AFTER the Page Directive:

    <%@ Register TagPrefix="Example" Namespace="CustomControls" Assembly = "CustomControls" %>
    

    Now, you should have a control named available to you. It might take it a minute to show up in intellisense.

提交回复
热议问题