Thursday, 5 December 2013

Adding content editor web part with default content through Visual Studio

Content editor web parts are very handy in many purposes and it is used a lot nowadays. A typical requirement that I have come across, is to add a content editor web part, with some default content to a page through visual studio. The requirement looks quite simple. But there are few areas which we need to keep in mind to get this working as expected.
One aspect being the HTML content within the CEWP does not render as HTML rather it renders as plain text. This is explained int the last step.

The steps which we need to follow are :

  • add a page to through visual studio ( for our example we will add a page to the site pages gallery)
  • add a web part zone to the page

<asp:Content id="Content5" ContentPlaceHolderId="PlaceHolderMain" runat="server">         <table class="ms-core-tableNoSpace ms-webpartPage-root" width="100%"> <tr> <WebPartPages:WebPartZone runat="server" Title="CETestWebPart" ID="CETestWebPart" FrameType="TitleBarOnly"><ZoneTemplate> </ZoneTemplate></WebPartPages:WebPartZone> </tr> </table></asp:Content>

  • modify the elements.xml to add the content editor web part properties. An easy workaround to get all the properties correct is to create a CEWP on a page using UI and then exporting it. Then open it in a notepad. 
    • Add an allUsersWebPart , add a guid. Under <![CDATA[ put all the code copied from the notepad, till <Content xmlns=""> 
  • within the content area add the default html in encoded format for the Content editor web part content. There are many HTML encoding decoding tool available online.
The final elements.xml will look like this :

 <File Path="SitePages\CEWebPart.aspx" Url="CEWebPart.aspx" Type="GhostableInLibrary" >
      <AllUsersWebPart WebPartOrder="1" WebPartZoneID="TestCEWP" ID="g_33268769_B61B_4665_8FF3_1BE038F0AB58">
        <?xml version="1.0" encoding="utf-8"?>
<WebPart xmlns:xsi="" xmlns:xsd="" xmlns="">
  <Title>Content Editor</Title>
  <Description>Allows authors to enter rich text content.</Description>
  <Height />
  <Width />
  <DetailLink />
  <HelpLink />
  <PartImageSmall />
  <MissingAssembly>Cannot import this Web Part.</MissingAssembly>
  <IsIncludedFilter />
  <Assembly>Microsoft.SharePoint, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>
  <ContentLink xmlns="" />
  <Content xmlns="">
     &lt;div&gt;test content for the CEWP &lt;/div&gt;       
        <PartStorage xmlns="" />

To make the content within CEWP render as HTML we need to encode the content. If we put direct HTML SharePoint will remove all HTML elements and everything will be put under a single DIV. Hence the HTML will be rendered as plain text.

You can find the whole project at this location