Skip to content

Instantly share code, notes, and snippets.

@naepalm
Created August 31, 2018 15:30
Show Gist options
  • Save naepalm/9c5d93231a79e1f9bc6a7ff0e6b7992d to your computer and use it in GitHub Desktop.
Save naepalm/9c5d93231a79e1f9bc6a7ff0e6b7992d to your computer and use it in GitHub Desktop.
Converts the core radio button automagically with ModelsBuilder from the value Id to the prevalue string. This does not use Dependency Injection, but it does work, so feel free to use it if you'd like!
using System;
using Umbraco.Core;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.PropertyEditors;
using Umbraco.Web;
namespace Offroadcode.Web.PropertyConverters
{
class RadioButtonValueConverter : PropertyValueConverterBase, IPropertyValueConverterMeta
{
private readonly UmbracoHelper _umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
public RadioButtonValueConverter()
{
}
public override bool IsConverter(PublishedPropertyType propertyType)
{
return "Umbraco.RadioButtonList".InvariantEquals(propertyType.PropertyEditorAlias);
}
public override object ConvertSourceToObject(PublishedPropertyType propertyType, object source, bool preview)
{
return source != null ? _umbracoHelper.GetPreValueAsString((int)source) : string.Empty;
}
public Type GetPropertyValueType(PublishedPropertyType propertyType)
{
return typeof(string);
}
public PropertyCacheLevel GetPropertyCacheLevel(PublishedPropertyType propertyType, PropertyCacheValue cacheValue)
{
return PropertyCacheLevel.Content;
}
}
}
@leekelleher
Copy link

Saves on an extra allocation too.
(When you become obsessed with allocations, you see them everywhere)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment