Support of IList<T> in EPiServer Content Delivery API
In Content delivery API AKA(Headless API), IPropertyModelHandler contains the list of all property models that should be in included in JSON, including images, Content Areas, and content references etc. But at this stage, our custom types based on PropertyList<CustomType> will not be included in the JSON output, the reason is obvious, as those are custom types. But it is easy to add those in JSON, below example, will walk you through the steps and will show the strength of Content Delivery API also.
Following Code is generally use to create IList<T> properties for pages and Blocks
public class Notes
{
[Display(Name = "Note 1")]
public string Note1 { get; set; }
[Display(Name = "Rank", Description = "1 - 10")]
[Range(1, 10)]
public int Rank { get; set; }
}
[PropertyDefinitionTypePlugIn]
public class NotesList : PropertyList<Notes>
{
protected override Notes ParseItem(string value)
{
return JsonConvert.DeserializeObject<Notes>(value);
}
public override PropertyData ParseToObject(string value)
{
ParseToSelf(value);
return this;
}
}
//Use it in your page/block
[CultureSpecific]
[Display(Name = "Notes", Description = "Notes", Order = 10)]
[EditorDescriptor(EditorDescriptorType = typeof(CollectionEditorDescriptor<Notes>))]
public virtual IList<Notes> PageNotes { get; set; }
Create a new type model
public class NotesPropertyModel : PropertyModel<IList<Notes>, NotesList>
{
public NotesPropertyModel(NotesList type) : base(type)
{
base.Value = type.List;
}
}
}
Register that type model in an initialization module.
[InitializableModule]
[ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
public class CustomPropertyModelIntialization : IInitializableModule
{
public void Initialize(InitializationEngine context)
{
var propertyModelHandler = ServiceLocator.Current.GetInstance<IPropertyModelHandler>();
propertyModelHandler.ModelTypes.Add(new TypeModel
{
ModelType = typeof(NotesPropertyModel),
ModelTypeString = "NotesPropertyModel",
PropertyType = typeof(NotesList)
});
}
public void Uninitialize(InitializationEngine context)
{
}
public void ConfigureContainer(ServiceConfigurationContext context)
{
}
}
Resulted JSON
"pageNotes": {
"value": [
{
"note1": "Happy development",
"rank": 5 },
{
"node1": "Happy Content Delivery API development",
"rank": 5,
}
],
"propertyDataType": "NotesList"
}
In case if you haven't explored Content Delivery API yet, follow the trail:
- https://mmols.io/getting-started-with-the-episerver-content-delivery-api/
- https://talk.alfnilsson.se/2018/04/24/tweaking-and-extending-serialization-from-episerver-content-delivery-api/
- https://world.episerver.com/blogs/Johan-Bjornfot/Dates1/2018/5/extended-routing-for-episerver-content-delivery-api/
- https://www.david-tec.com/2018/06/episerver-as-headless-episerver-ascend-2018-presentation/
Comments