I created custom SXA rendering with variants but Model.VariantFields return null.
my controller
public class NotificationController : VariantsController
{
protected NotificationRepo notificationRepo
{ get; set; }
public NotificationController()
{
}
public NotificationController(NotificationRepo Repository)
{
notificationRepo = Repository;
}
protected override object GetModel()
{
notificationRepo = new NotificationRepo();
return notificationRepo.GetModel();
}
}
and the Repository code
public class NotificationRepo : ListRepository, IModelRepository, IControllerRepository, IAbstractRepository<IRenderingModelBase>
{
public Notification NotificationItem
{
get
{
try
{
Notification notification = new Notification();
string dataSourceId = RenderingContext.CurrentOrNull.Rendering.DataSource;
Item dataSource;
if (dataSourceId != null)
{
dataSource = Sitecore.Context.Database.GetItem(dataSourceId);
MultilistField RelatedConetnt = dataSource.Fields["Related Content"];
if(RelatedConetnt != null)
{
Item NotifiactionItem = RelatedConetnt.GetItems().ToList().FirstOrDefault();
notification.Title = NotifiactionItem.Fields["Title"] != null ? NotifiactionItem.Fields["Title"].Value : string.Empty;
notification.Description = NotifiactionItem.Fields["Description"] != null ? NotifiactionItem.Fields["Description"].Value : string.Empty;
notification.Status = NotifiactionItem.Fields["Status"] != null ? NotifiactionItem.Fields["Status"].Value : string.Empty;
}
}
return notification;
}
catch(Exception ex)
{
Sitecore.Diagnostics.Log.Error("NotificationRepo : Error in retriving Notification data", ex);
return null;
}
}
}
public override IRenderingModelBase GetModel()
{
Notification model = new Notification();
FillBaseProperties((object)model);
model= this.NotificationItem;
return (IRenderingModelBase)model;
}
}
and my model
public class Notification : VariantsRenderingModel
{
public String Title { get; set; }
public String Description { get; set; }
public String Status { get; set; }
}
and I created simple view to test the custom rendering
@foreach (BaseVariantField variantField in Model.VariantFields)
{
@Html.RenderingVariants().RenderVariant(variantField, Model.Item, Model.RenderingWebEditingParams, Model)
}
I get object reference to null error in the "@foreach
" line where Model.VariantFields
is null. When I debugged I found that Model.Item
is also null.
I need to know why these properties have null??