How to register custom server control on ASP.NET page

I have a project and I am trying to register a custom server control (there is no .ascx file) on the page. I am currently using

Class Declaration

namespace MyApp.Controls{
    public class CustomControl: WebControl{
        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);
        }
    }
}

On my page,

<%@ Register TagPrefix="myControls" Namespace="MyApp.Controls" %>
<myControls:CustomControl runat="server" Text="What up!" />

I receive a Parser Error, with the message “Unknown server tag ‘myControls:CustomControl’.”

What am I doing wrong?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Well, if this control is in another class library, or even if it’s in the same one, it wouldn’t be a bad idea to specify control’s assembly in @Register:

<%@ Register TagPrefix="myControls" Namespace="MyApp.Controls" Assembly="MyApp" %>
<myControls:CustomControl runat="server" Text="What's up!" />

Clean and rebuild your solution too in order to verify everything is compiled rightly!

Method 2

If your control will be reused on several pages, you may want to register it in web.config, as one of system.web/pages/controls subelements instead of copy-pasting the same <@Register tag in all affected pages.

web.config:

<system.web>
  <pages ...>
    <controls>
      ...
      <add tagPrefix="myCompany" namespace="MyCompany.Whatever.Controls" assembly="Whatever"/>
    </controls>

thepage.aspx:

<myCompany:ControlClassName ID="TheStuff" runat="server" ... />

Method 3

You should put your control either under the App_Code folder (in the case if the control not in assembly) or add a reference to assembly where this control is:

<%@ Register TagPrefix="myControls" Namespace="MyApp.Controls"
      Assembly="SomeAssembly" %>

But guessing, your control not under the App_Code folder.

Method 4

Add an assembly attribute to your register tag


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x