Views: 9331
Number of votes: 4
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; }
Mar 10, 2014

( 3/10/2014 10:08:19 AM)


( By Vincent, 3/10/2014 11:12:42 AM)

IMO, I prefer to set these values in one place as you override the SetDefaultValues function, it applies to the new page instance only once. If you make them as attribute, it will mislead the other developers as they may try to use this to alter the property's value.

( 3/10/2014 11:47:15 AM)

Simple and good idea! Thanx!

( By valdis, 3/10/2014 1:58:59 PM)


Gayathri Saravanan
( By Gayathri Saravanan, 3/13/2014 5:01:24 PM)


Per Magne Skuseth
( By Per Magne Skuseth, 5/12/2014 4:29:12 PM)

Thanks! However, Code Monkey does have a really good point, which should be seriously considered before thinking about implementing something like this.

Henrik Fransas
( By Henrik Fransas, 6/22/2015 2:53:53 PM)

Have not seen this before, Great work as always Per Magne!

Shoma Gujjar
( By Shoma Gujjar, 7/29/2015 2:07:20 PM)


Thanks for the great post. It works well however, if i make my property [Required] , it does not apply the default attribute. Is this an issue?

( By nitinanand, 1/23/2019 12:20:29 PM)

Any way to set default values to new properties on existing pages?

Please login to comment.