I needed to set default values for a couple of my EPiServer 7.5 block and page properties today, and found Per Mange Skuseth‘s article on Attribute-based default values. I really like Per’s way of dealing with them, as you get to have each default value in connection with the property that it will affect, rather than stoving them away in some obscure method override chunk that nobody will ever think of looking at; plus it reminded me of the old days.
The code wouldn’t run as it was in my solution for some reason, so I had to alter it somewhat. I also needed the same functionality for my EPiServer block types, so I extracted the logic into a BaseTypeService class and added it to my project’s block base class as well.
Thanks Per for saving me some time today :)
MyPageBase.cs
public abstract class MyPageBase : PageData { public override void SetDefaultValues(ContentType contentType) { ServiceLocator.Current.GetInstance<IBaseTypeService>().SetDefaultValuesFor(this); base.SetDefaultValues(contentType); } }
MyBlockBase .cs
public abstract class MyBlockBase : BlockData { public override void SetDefaultValues(ContentType contentType) { ServiceLocator.Current.GetInstance<IBaseTypeService>().SetDefaultValuesFor(this); base.SetDefaultValues(contentType); } }
IBaseTypeService.cs
public interface IBaseTypeService { void SetDefaultValuesFor(ContentData contentType); }
BaseTypeService .cs
public class BaseTypeService : IBaseTypeService { public void SetDefaultValuesFor(ContentData contentType) { var properties = contentType.GetType().BaseType.GetProperties(); foreach (var property in properties) { var defaultValueAttribute = (DefaultValueAttribute[]) property.GetCustomAttributes(typeof(DefaultValueAttribute), false); if (defaultValueAttribute != null && defaultValueAttribute.Length > 0) { contentType[property.Name] = defaultValueAttribute[0].Value; } } } }