Insert and initialize a user control from an .aspx page

June 21, 2012 » Trackback

There are a couple of ways to initialize a user control and insert it onto an .aspx page. In the past I was using the method outlined in a previous post (Binding a User Control to a ContentPlaceHolder from an .aspx file in VB.NET) which has the ContentPlaceHolders present on the MasterPage files. The following method allows for them to be placed directly onto an .aspx page.

To initialize the UserControl, this code should be placed just below the initial line of code on your .aspx page.

<%@ Register Src="~/SocialMedia.ascx"   TagName="Social" TagPrefix="SocialControl" %>

The Src should be the path to your .ascx file, whilst the TagName and TagPrefix are relatively unimportant – yet you want to keep them related.

<SocialControl:Social id="SocialMedia" runat="server"></SocialControl:Social>

Then you place the code above wherever you want your UserControl to appear. As you can see, the opening and closing tags are the TagPrefix and TagName separated by a colon. If you are using multiple UserControls for similar functionality then you may wish to keep the TagPrefix the same for increased organization of your code.

  • Billy

    I think there’s a bug in that code. Makes it very confusing

    • Danny

      Thank you for pointing that out Billy, it has now been fixed!

  • Billy

    Wow fixed now, great speedy response!

    • Danny

      Glad to help!