In this tutorial, you will learn how to create a custom Episerver property. Out of the box, Episerver provides a number of useful properties that you can use for content modelling purposes. The default properties include PropertyBoolean
(Boolean), ContentArea
, PropertyCategory
(Category), and PropertyContentReference
(Content Reference). What happens if you want to model some data within the CMS that doesn't quite fit into one of the pre-existing properties? In these instances you will need to create something custom. In this tutorial, you will learn how to do that 🔥🔥🔥
The property you will learn to create is going to be for back-end storage purposes only. I'm going to skip the code to render the property within the CMS in this tutorial. To build a custom UI for this property, you need to write some HTML and some Javascript using Dojo. I explain how to do the Dojo part in this tutorial.
PropertyData
All Episerver properties need to inherit from the PropertyData
base class. This class can be found in the EPiServer.Core
namespace within Episerver.dll
. To create a custom property, create a new class and inherit from PropertyData
. PropertyData
has a number of properties and methods you can override. If you want to create a new type, say a List<>
, you will need to override the PropertyValueType
and the Value
property. The clever thing about this process is that it allows you to define any object type you desire. The Value
property takes an object
so you can do whatever boxing/unboxing/typing logic you want. The PropertyValueType
is then used to tell Episerver what type of object is returned
Creating a List Property
The property we will create today will store data in a list. The code to create this property is shown below:
In order to use a List<int>
, you will need to serialise and deserialise data within the code. Episerver only persists data into the database in a string
format. If you tried to save a List<int>
directly to the database Episerver would throw an exception.
There is a limit to the size of data that can be stored against a property. To store a list, you will want to make sure the data is not truncated. You can do this by using the PropertyLongString
as the backing type. Using this property will provision the largest amount of space within the database. PropertyLongString
will be stored as a NVarChar(Max)
in the database.
On Line 4, override PropertyValueType
and return the type of item we want Episerver to cast to. In this example, it is a List<int>
. On Line 12, override the Value
property. In here, you can use Json.Net to serialise the List<int>
to a string
in order to save it.
If you want some more information about this, I have previously written about Json.Net in this article, How To Store Multiple Objects Against A LineItem Or The Cart In Episerver Commerce. In the set
part of the property, you need to add the code to deserialize the string and convert it back to a List<int>
.
Happy Coding 🤘