Skip to content

Instantly share code, notes, and snippets.

@leekelleher
Forked from jamiepollock/ExtensionMethods.cs
Last active August 29, 2015 14:08
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 leekelleher/8e85a1020179edfad29a to your computer and use it in GitHub Desktop.
Save leekelleher/8e85a1020179edfad29a to your computer and use it in GitHub Desktop.

The following code is intended for use as an overloaded extension for the GetPropertyValue<T>(string alias, bool recurse) method when getting strongly typed values back.

This example uses Archetype where in Umbraco v7.1.8 calling such a property value recursively returns an ArchetypeModel with 0 fieldsets.

There could be other possible applications for allowing a developer to determine the logic when GetPropertyValue<T>(string alias, bool recurse) is trying to get a value recursively but accepts it.

using Archetype.Models;
using My.Website.ExtensionMethods;
using System.Linq;
using System.Web.Mvc;
using Umbraco.Web.Models;
using Umbraco.Web.Mvc;
namespace My.Website.Controllers
{
public class MyPageController : RenderMvcController
{
public override ActionResult Index(RenderModel model)
{
var propertyGotRecursively = model.Content
.GetPropertyValue<ArchetypeModel>("archetypeBuiltProperty", true, x => x.Fieldsets.Any());
var viewModel = new
{
MyValue = propertyGotRecursively
};
return View(viewModel);
}
}
}
using System;
using System.Linq.Expressions;
using Umbraco.Core.Models;
using Umbraco.Web;
namespace My.Website.ExtensionMethods
{
public static class UmbracoExtensions
{
public static T GetPropertyValue<T>(this IPublishedContent content, string alias, bool recurse, Func<T, bool> isValid, T defaultValue = default(T))
{
if (content.HasProperty(alias))
{
var value = content.GetPropertyValue<T>(alias);
if (isValid(value))
{
return value;
}
}
if (content.Parent != null)
{
return content.Parent.GetPropertyValue(alias, true, isValid);
}
return defaultValue;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment