Search code examples
sitecoresitecore8sitecore-mvc

Getting ID of Sitecore control from controller


I am trying to get a field value associated with a control instance in Sitecore within an MVC controller. I seem to be struggling to find the correct syntax.

I tried this I tried using this within the Sitecore controls MVC controller, but it comes back with a null reference exception for "Item":

Guid campaignID = new Guid(Constants.Marketing.CAMPAIGNID);
Sitecore.Mvc.Presentation.RenderingContext renderingContext = new Sitecore.Mvc.Presentation.RenderingContext();
string currentCampaign = renderingContext.PageContext.Item.Fields[campaignID.ToString()].Value;

Solution

  • You should not create a new instance of RenderingContext class.

    You should use RenderingContext.Current. Try the code below:

    Item datasourceOrContextItem = RenderingContext.Current.Rendering.Item;
    string currentCampaign = datasourceOrContextItem[campaignID.ToString()].