By default, when you create a visual web part in a SharePoint 2010 project, Visual Studio adds a user control for you and performs the necessary plumbing to ensure it gets deployed to the Control Templates directory in the 14 hive. This is all very fine until you want to model a dialog or secondary display mode as another user control; VS does not offer an easy or obvious way to add a user control inside a web part.
I figured out the procedure for this a few months ago at work, and it has been living on our internal wiki since then, so I thought I’d post it here. It assumes you want to create a user control called UserControl.ascx either directly inside a web part, or inside a folder inside the web part (given by OptionalFolderPath).
- Right click your project and add a new user control.
- Drag the user control from the default location (ControlTemplates\ProjectName) to your web part.
- Edit the web part .spdata file in the following way:
- The target for the new user control is probably set to ProjectName\WebPart instead of CONTROLTEMPLATES\ProjectName\WebPart, like the original user control. Change it to match.
- The source for the new user control is probably set to something like ‘..\WebPart\OptionalFolderPath\UserControl.ascx’. If you want, you can remove the first two redundant segments.
- Change the namespace of the user control from the godawful ControlTemplates one, to one of your choice (generally, the same as your web part). If you have Resharper, you can do this cleanly in one swipe. Otherwise, manually:
- Rename the namespace in your user control code-behind
- Update the Control directive near the top of the ascx accordingly.
- Reference your new user control. The path will be something like “~/_CONTROLTEMPLATES/ProjectName/WebPart/OptionalFolder/UserControl.ascx”:
- If you’re referencing it from your web part .cs, call TemplateControl.LoadControl with the above path.
- If you’re referencing it from your original user control, add a reference like: <%@ Register TagPrefix=”Controls” tagName=”UserControl” src=above path %>