Wednesday, October 24, 2012

Adding a custom CSS file to your Visual Web Part

If you would like to add a custom CSS file to a Visual Web Part that allows the styling of the web part to remain consistent no matter where it's installed, you can do so via the following steps:

  1. Using Visual Studio 2010, open your Visual Web Part solution
  2. In Solution Explorer, right-click on the project and select Add -> SharePoint "Layouts" Mapped Folder
  3. Right-click on the newly created Layouts folder and select Add -> New Folder
  4. Edit the name from "NewFolder1" to "1033"
  5. Right-click on the "1033" folder and select Add -> New Folder
  6. Edit the name from "NewFolder1" to "Styles"
  7. Right-click on the "Styles" folder and select Add -> New Folder
  8. Edit the name from "NewFolder1" to the name of your Project (i.e. MyProject in this example)
  9. Right-click on the "MyProject" folder and select Add -> New Item...
  10. Under the Installed Templates section, expand Visual C# and click on Web
  11. Click on the Style Sheet icon, update the name of your style sheet (i.e. Standard.css in this example), and click Add
  12. You may now enter the appropriate style sheet rules in this file and save the changes
During the deployment of your Visual Web Part, the custom style sheet will be deployed directly to the SharePoint farm under the following location on the web front end servers:  C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\1033\STYLES\MyProject.

Now, to reference the style sheet in your Visual Web Part, you may do so via the following steps:
  1. Open your Visual Web Parts .ascx file
  2. After the "<%@ Control" tag, add the following line:  <SharePoint:CssLink ID="cssLink1" runat="server" DefaultUrl="MyProject/Standard.css" />
  3. Save the change
At this point, you will be able to reference the new style sheet within the controls on your .ascx page.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.