Skip to content

Instantly share code, notes, and snippets.

@robertjf
Last active April 23, 2018 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertjf/ef0f4a15c0109557c98f2f842edf84b5 to your computer and use it in GitHub Desktop.
Save robertjf/ef0f4a15c0109557c98f2f842edf84b5 to your computer and use it in GitHub Desktop.
Umbraco ContentModelExtensions

Umbraco ContentModelExtensions Reference

Typical usage:

Umbraco Razor Views:

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    ContactPage page = Model.Content.As<ContactPage>();
}

Getting a list of content nodes from a property:

IEnumerable<Article> related = Model.Content.GetPropertyValue<IEnumerable<IPublishedContent>>("relatedArticles")
                                            .As<Article>();
using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core.Models;
namespace Project.Code.Models.Content
{
public static class ContentModelExtensions
{
/// <summary>
/// Create an instance of T from the content
/// </summary>
/// <typeparam name="T">class to convert to</typeparam>
/// <param name="content"></param>
/// <returns></returns>
public static T As<T>(this IPublishedContent content)
{
// optimised if the content object is already the expected type
if (content == null || content is T)
{
return (T)content;
}
// supports returning Interface-based Partial Document Type definitions
// i.e. ContentPage : ISEO can be returned as an ISEO instance.
if (typeof(T).IsInterface)
{
return default(T);
}
return (T)Activator.CreateInstance(typeof(T), content);
}
/// <summary>
/// Convert the list of content items to type T
/// </summary>
/// <typeparam name="T">class to convert to</typeparam>
/// <param name="content"></param>
/// <returns></returns>
public static IEnumerable<T> As<T>(this IEnumerable<IPublishedContent> content)
{
if (typeof(T) == typeof(IPublishedContent))
return (IEnumerable<T>)content;
return (content ?? Enumerable.Empty<IPublishedContent>()).Select(t => t.As<T>());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment