Saturday, March 24, 2012

Use App_LocalResources in visual web parts

In this post I will describe how to use standard ASP.Net technique for adding localized literals to the UI. When you create visual web part in VS 2010 Sharepoint project several files are added to the project:

  • Web part class
  • User control layout file (ascx)
  • Codebehind for user control
  • Sharepoint files for provisioning web part to site collection

image

If you will package project to wsp file and check structure inside it (you can also check it inside pkg subfolder in your project folder), you will find that ascx file will be copied to 14/ControlTemplates sub folder: in our example it is 14/ControlTemplates/SharePointProject1/VisualWebPart1. This is exactly the path which is used in LoadControl() method in web part class:

   1: public class VisualWebPart1 : WebPart
   2: {
   3:     private const string _ascxPath =
   4:         @"~/_CONTROLTEMPLATES/SharePointProject1/VisualWebPart1/VisualWebPart1UserControl.ascx";
   5:  
   6:     protected override void CreateChildControls()
   7:     {
   8:         Control control = Page.LoadControl(_ascxPath);
   9:         Controls.Add(control);
  10:     }
  11: }

In order to use standard ASP.Net local resources in ascx file we need to create App_LocalResources sub folder in the 14/ControlTemplates/SharePointProject1/VisualWebPart1 folder and put resx file with the following name: VisualWebPart1UserControl.ascx.resx. After this we can add localized literals into user control like this using standard ASP.Net convention:

   1: <asp:Label runat="server" Text="<%$Resources:Title%>" />

How to add App_LocalResources to the VS Sharepoint 2010 project in order to copy it to the VisualWebPart1 folder after provisioning? Of course we can add Sharepoint mapped folder to the project manually, then create VisualWebPart1 folder in it and put App_LocalResources there:

image

When we will package our wsp VS will merge user control and App_LocalResources into single folder. However the problem with this approach is that files are spread across project: web parts files are stored in one place while resx files for web parts in another.

VS allows to add local resources directly into visual web part project item:

image

After that you need to make extra step: in the properties of resx file set Deployment Type to TemplateFile and change Path under Deployment Location to the folder of your control (in our example it is ControlTemplates/SharePointProject1/VisualWebPart1/App_LocalResources):

image

With this approach all related files will be located in the same place in the project and will be copied to the correct folder during provisioning.

No comments:

Post a Comment