The Web User Control in ASP.NET is a powerful element to effectively reuse design components within the project. However, there is no standard way to create a Web User Control Library which could be used across mutiple web projects. In my current scenario I want multiple web applications to share the user controls.
Scott Guthrie has explained this here Building Re-Usable ASP.NET User Control and Page Libraries with VS 2005, but he is suggesting to publish the user controls project separately and then copy paste the files in your actual project. This is not very practical if you have multiple applications and a team which is constantly updating the user controls and the applications and continuously checking-in latest controls.
So here goes the solution.
- You need to create a Web Application Project instead of a Website project for your User Controls. The reason for this is that the Website project that you create with Visual Studio 2005 cannot be consumed by other projects within the solution. Moreover, since there is no project file, you cannot add Pre-Build/Post-Build events to the project. You will have to download Web Application Project Template for visual studio 2005 since Visual Studio 2005 does not provide this in def ault installation.
- OK, after you have the Web Application Project template, create two projects, one Web Application Project (UserControlLibrary) for the User Controls and another ASP.NET Website as shown in the figure.
- Now Build the “UserControlLibrary” project which will generate a single DLL (UserControlLibrary.dll) for this project. Now Add a Reference of this project to the other website project.
- In order to copy the ASCX files of the controls in UserControlLibrary to the website project, add a Post-Build Event for the UserControlLibrary, to copy all ASCX files to the Website project.
- Now add a UserControls folder under both projects and keep all your user controls under the UserControls folder in the UserControlLibrary. Go to the properties of the UserControlLibrary project and then to the Compile Tab, open the Build Options and add the following to the Post Build Event.
copy “$(ProjectDir)UserControls\*.ascx” “$(SolutionDir)WebSite\UserControls\” /Y
- After adding the post-build event, whenever you compile your UserControlLibrary project, the DLL will be updated in the Website project because of the reference and the ascx will be copied by the Post Build Event that we just added.