• Publisert
  • 2 min

PropertyXhtmlString and WebParts

I get a lot of questions concerning WebParts used with EPiServer. The most common question is how to use the PropertyXhtmlString and text editor (TinyMCE) in a WebPart. I'll provide examples using both WebControl and UserControl.

WebControl

public class EditorPart : PropertyDataWebPartBase
{
   [Personalizable, IsRequired]
   public SerializablePropertyXhtmlString MainBody { get; set; }

   public EditorPart()
   {
      MainBody = new SerializablePropertyXhtmlString {
         EditorToolOptions = EditorToolOption.All ^ EditorToolOption.Font
      };
   }

   protected override void OnPreRender(EventArgs e)
   {
      var propertyControl = MainBody.CreatePropertyControl();
      propertyControl.PropertyData =
         new PropertyXhtmlString(MainBody.Value as string);
      Controls.Add(propertyControl as Control);
   }
}

UserControl

The .ascx file simply contains a PlaceHolder

<asp:PlaceHolder runat="server" ID="uxEditor" />

And the code behind is very similar to the WebControl

public partial class UCEditorPart : UserControlWebPartBase
{
   [Personalizable, IsRequired]
   public SerializablePropertyXhtmlString MainBody { get; set; }

   public UCEditorPart()
   {
      MainBody = new SerializablePropertyXhtmlString {
         EditorToolOptions = EditorToolOption.All ^ EditorToolOption.Font };
   }

   protected override void OnPreRender(EventArgs e)
   {
      base.OnPreRender(e);
      var propertyControl = MainBody.CreatePropertyControl();
      propertyControl.PropertyData =
        new PropertyXhtmlString(MainBody.Value as string);
      uxEditor.Controls.Add(propertyControl as Control);
   }
}

For both approaches you'll need the SerializablePropertyXhtmlString

[Serializable]
public class SerializablePropertyXhtmlString : PropertyLongString
{
   private EditorToolOption _editorToolOptions;

   public override IPropertyControl CreatePropertyControl()
   {
      return new PropertyXhtmlStringControl();
   }

   public override EPiServer.Editor.EditorToolOption EditorToolOptions
   {
      get
      {
         if (PrincipalInfo.Current.IsPermitted(Permission.EditorUnlimitedFunctions))
         {
            return EditorToolOption.All;
         }
         return _editorToolOptions;
      }
      set
      {
         base.ThrowIfReadOnly();
         _editorToolOptions = value;
      }
   }

   public override object Value
   {
      get
      {
         var prop = new PropertyXhtmlString(base.Value as string);
         return prop.ToString();
      }
      set
      {
         var prop = new PropertyXhtmlString(value as string);
         base.Value = prop.Value;
      }
   }
}

I hope this was helpful. The source is also downloadable.