Sunday, July 6, 2008

Creating an .ascx library in ASP.net

Here is a solution that will enable you to create .dlls for those useful re-usable web user controls you've created and use them in future asp.net web applications.

The msdn has a guide over here: http://msdn.microsoft.com/en-us/library/aa479318.aspx

lets assume you already have some web user controls in a asp.net website, if you dont, create some...
Heres how I got it to work:

  1. For your .ascx control, embed your code behind into the page in a script block.
    <script runat="server">

    You will need to modify the Control tag, you should only use the Language and ClassName attributes. eg.
    <%@ Control Language="C#" ClassName="DKCS.FileUploadManager"%>
    Notice how I have prefixed the ClassName attribute with my namespace DKCS.
  2. make sure the code compiles and test your control. Its a good idea to delete the code behind file if there was one being used previously.
  3. Publish your website. The purpose of doing this is to generate the dlls for your controls.
    You will need to use these settings:
    -Deselect Allow this precompiled site to be updateable
    -Select Use fixed naming and single page assemblies
    -I also deselected enable strong naming on precompiled assemblies. This is useful if you want to put your control in the GAC.
  4. Now browse to the location where you published your site to, look in the bin directory and you'll see some dll's in there. Your control will be named something like this:
    App_Web_fileuploadmanager.ascx.cdcab7d2.dll

    And there you have it, a dll with your control in it. It is actually a custom control but it has not lost any of its functionality as a web user control.

To use the dll:

  1. Add a reference to the dll in your website.
  2. On the page you want to use the control you will need to use the Register tag. Mine was configured like this:

    <%@ Register TagPrefix="DKCS" Namespace="DKCS" Assembly="App_Web_fileuploadmanager.ascx.cdcab7d2" %>
  3. You should now be able to use your control on the page like this:



    The designer might not render it but it should be ok once you run it in a browser.

No comments: