Allow Content Model attribute

API Reference: AllowContentModelAttribute Class

The AllowContentModelAttribute can be applied to page sections and (nested) content model properties. The attribute specifies which content models are allowed for a page section or content model property. This applies to both single content items as well as collections of content items.

The attribute is only necessary when the type of the property allows content models of multiple types, e.g. in case of a base class or interface. If the type is a (sealed) class that is not used as a base class for other content models, the type itself already restricts the property to a single content model, and the attribute is not necessary.

Usage

Decorate the page model class with the AllowContentModelAttribute. Pass the allowed content model types in the constructor. The types must be concrete class types that derive from the model property type or interface. Passing a type that does not derive from the model property type causes an invalid configuration error on startup.

The attribute can be applied multiple times. All types from all applied attributes are added to the allowed content model list. The attribute is not inherited, so any allowed content models that you have specified on a base class of this model will have to be specified explicitly on derived model classes.

Default Convention

If AllowContentModelAttribute is not specified on a page section or content property, all content models that are or derive from the property type are allowed.

Example

public class ContentPage: IPageModel
{
    // Restricts allowed content models to 3 types.
    [AllowContentModel(typeof(ParagraphContent), typeof(SummaryContent), typeof(ImageContent))]
    public List<IContentModel> Modules { get; set; }

    // Allows 2 content model types that must derive from BaseContent, but not BaseContent itself.
    [AllowContentModel(typeof(ParagraphContent), typeof(SummaryContent))]
    public List<BaseContent> { get; set; }

    // By convention, allows any content model that is of type BaseContent or derives from it.
    public BaseContent Content { get; set; }

    // By convention, allows any content model that is available in the system.
    public IContentModel AnyContent { get; set; }

    // SeoContent is a sealed class; AllowContentModelAttribute is not required because the property type already restricts the content to a single model.
    public SeoContent Seo { get; set; }
}

This example specifies allowed content models for the ContentPage page model. Content model classes with nested content are similar but implement IContentModel.