API Reference: DefaultValueAttribute Class

The DefaultValueAttribute can be applied to content model properties. The attribute specifies the default value of a property when it is undefined. The default value will only be applied to new content items when editing in the back office and sets the default value for the property only once. Changing the default value for a property has no effect on existing content items.

A default value can only be assigned to value type properties. If DefaultValueAttribute is not specified, the default value of the property will be the default value of the type (i.e. default(T)).

Alternatively to setting DefaultValueAttribute, you can initialize a content model property to a default value. In this case, the model instance will have the default initialized value if no value for the property exists on the content item. This does not populate the content item with a default value or render a default value in the back office. However, it can be changed later with a different initialized value. This has no effect if a content property is required since the back office will ensure that a value is always saved.

Usage

Decorate the property with the DefaultValueAttribute. Pass the default value in the constructor. The parameter is of type object so the attribute can be used for different property types. In the constructor, you will need to provide a value that is of the actual property type. If the default value is not of the correct property type this will cause an invalid configuration error at system startup.

Example

public class SampleContent: IContentType
{
    // Specifies a default string value.
    [DefaultValue("Enter a description.")]
    public string Description { get; set; }

    // Default value will be 0 by convention.
    public int Count { get; set; }
}