This is my API Controller:
[HttpGet]
public JsonResult FeaturedCategories()
{
Database WebDB = Sitecore.Configuration.Factory.GetDatabase("web");
var dataSourceId = RenderingContext.Current.Rendering.DataSource;
Item dataSourceItem = WebDB.GetItem(new ID(dataSourceId));
if (dataSourceItem == null) return new JsonResult() { Data = string.Empty, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
var model = GetFeaturedCategoriesModel(dataSourceItem);
return new JsonResult() { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
private static FeaturedCategoriesModel GetFeaturedCategoriesModel(Item dataSourceItem)
{
FeaturedCategoriesModel model = new FeaturedCategoriesModel();
List<CardDetails> cardDetailsList = new List<CardDetails>();
MultilistField cardLists = dataSourceItem.Fields["Categories"];
model.categoryTitleString = dataSourceItem["CategoryTitle"];
model.categoryDescString = dataSourceItem["CategoryDescription"];
if (cardLists != null && cardLists.Count > 0)
{
foreach (Item cardItems in cardLists.GetItems())
{
string categoriesCardTitle = cardItems["CategoryCardTitle"];
ImageField categoriesCardImageMediaURL = cardItems.Fields["CategoryCardImage"];
string categoriesCardImage = MediaManager.GetMediaUrl(categoriesCardImageMediaURL.MediaItem);
LinkField categoriesAnchor = cardItems.Fields["CategoryPageLink"];
string categoriesAnchorUrl = categoriesAnchor.GetFriendlyUrl();
var CardDetailsObj = new CardDetails()
{
cardTitleString = categoriesCardTitle,
cardImageField = categoriesCardImage,
cardURL = categoriesAnchorUrl,
};
cardDetailsList.Add(CardDetailsObj);
}
}
model.CategoryCardDetails = cardDetailsList;
return model;
}
}
This is the error:
Attempt to retrieve context object of type 'Sitecore.Mvc.Presentation.RenderingContext' from empty stack.
WebDB.GetItem(new ID(dataSourceId))
?