从控制器获取 Sitecore 控件的 ID

Getting ID of Sitecore control from controller

我正在尝试获取与 MVC 控制器内 Sitecore 中的控件实例关联的字段值。我似乎在努力寻找正确的语法。

我试过了 我试过在 Sitecore controls MVC 控制器中使用它,但它返回时出现 "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;

您不应创建 RenderingContext class 的新实例。

你应该使用 RenderingContext.Current。试试下面的代码:

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

我建议控制器有一个如下所示的基本控制器:

  public class ControllerBase : Controller
  {
    /// <summary>
    /// Gets the current rendering.
    /// </summary>
    /// <value>
    /// The Sitecore controller rendering.
    /// </value>
    protected virtual Rendering Rendering
    {
        get
        {
            return RenderingContext.CurrentOrNull != null ? RenderingContext.Current.Rendering : null;
        }
    }
  }

当您创建一个继承自它的新控制器时,您将拥有项目的渲染数据源。