Views: 4855
Number of votes: 3
Average rating:

Attribute-based default values

Default property values on content in EPiServer are set by overriding SetDefaultValues. In an attempt to make my model classes a bit tidier, by not having to do the override in lots of places, I wrote a little piece of code which enables the use of the DefaultValue attribute (found in System.Component), like so:

[DefaultValue("It's all in the hips")]
public virtual string Tip { get; set; }


Below is the code that is needed in order to make this work. In this particular case, SitePageData is the base class for all my page types.

public abstract class SitePageData : PageData
    public override void SetDefaultValues(ContentType contentType)
        PropertyInfo[] properties = GetType().BaseType.GetProperties();
        foreach (var property in properties)
            var defaultValueAttribute = property.GetAttribute<DefaultValueAttribute>();
            if (defaultValueAttribute != null)
                this[property.Name] = defaultValueAttribute.Value;


Now, as long as my page types inherits SitePageData, the attribute can be utilized. Example:

[ContentType(DisplayName = "Article", GUID = "ED1B0CD5-1307-49FA-853F-ADF46CCEE1CE")]
public class ArticlePage : SitePageData
    public virtual bool HideSomething { get; set; }
    public virtual int MaxNewsItems { get; set; }
    [DefaultValue("Bla bla bla")]
    public virtual XhtmlString MainBody { get; set; }
  Please login to post a comment