【问题标题】:Sitecore glassmapper how to fetch the datasource from the renderingSitecore glassmapper 如何从渲染中获取数据源
【发布时间】:2019-01-23 13:07:58
【问题描述】:

需要关于我想使用 glassmodel 渲染项目的 Sitecore 渲染的建议。

我有一个页面,它有很多渲染,每个渲染都有与之关联的数据源。

我知道下面的语句会给我当前上下文,而不是数据源项。

var context = new SitecoreContext();
            Model = context.GetCurrentItem<HomePage>();

解决我的查询的最佳选择是什么?我给过this的文章。但是我真的不相信这种方法,因为我正在使用 IoC(温莎城堡)并且必须为每种方法编写单元测试用例。以后我可能不得不模拟这些对象。我正在寻找我将使用接口而不是类的方法。

感谢您的帮助。

【问题讨论】:

    标签: sitecore sitecore8 sitecore-mvc glass-mapper


    【解决方案1】:

    如果您的控制器源自GlassController,您可以使用GetDataSourceItem&lt;I..&gt;()。这将为您提供数据源。

    【讨论】:

    • 这正是我想要的。谢谢@Gatogordo
    【解决方案2】:

    如果您使用 Glass Mapper 5,文档不再提及使用 GlassController。您可以像下面这样使用 IMvcContext:

    using System.Web.Mvc;
    using Glass.Mapper.Sc.Web.Mvc;
    
    public class TitlesController : Controller
    {
        public ActionResult Index()
        {
            IMvcContext mvcContext = new MvcContext();
    
            // will return the DatasourceItem if set, otherwise the page context is returned
            Titles model = mvcContext.GetRenderingItem<Titles>();
    
            Titles dsModel = mvcContext.GetDataSourceItem<Titles>();
    
            return View(model);
        }
    }
    

    【讨论】:

      【解决方案3】:

      添加到 Gatogorodo 的答案

      如果您的控制器是从 GlassController 派生的,或者如果您在 GlassView 中,则可以使用 this.DatasourceItem 获取数据源。

      this.GetDataSourceItem&lt;Model&gt;() 将为您提供所需的模型,该模型可能是项目模板的基本模板之一。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多