API Reference: AllowContentTypeAttribute Class

The AllowContentTypeAttribute can be applied to content model properties. The attribute specifies which content model types are allowed for a nested content model property. This applies to both single content items as well as collections of content items. The content property must be of type IContentType, a derived type, or a collection thereof.

The attribute is only necessary when the type of the property allows content models of multiple types, for example 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.

If AllowContentTypeAttribute is not specified on a content model property, all content models that are or derive from the property content type are allowed by default.

Usage

Decorate the content model property with the AllowContentTypeAttribute. Pass the allowed content model types in the constructor. The attribute constructor accepts one or more Type values as a params Type[] parameter. Alternatively, the attribute can be set multiple times on the property.

The types must be concrete class types that derive from the model property type or interface (ultimately implementing IContentType). Passing a type that does not derive from the model property type causes an invalid configuration error on startup.

Content types can be either assets (decorated with Asset attribute) or embedded nested content (no type attribute). See content models for an explanation of how nested content works.

Example

The following example specifies allowed content model types for ContentPage content model properties.

[Page]
public class ContentPage: IContentType
{
    // Restricts allowed content models to 3 types.
    [AllowContentType(typeof(ParagraphElement), typeof(SummaryElement), typeof(ImageElement))]
    public IReadOnlyList<IContentType> Modules { get; set; }

    // Allows 2 content model types that must derive from BaseElement, but not BaseElement itself.
    [AllowContentType(typeof(ParagraphElement), typeof(SummaryElement))]
    public IReadOnlyList<BaseElement> Elements { get; set; }

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

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

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