【问题标题】:Why Glass Mapper Returning Null Values?为什么 Glass Mapper 返回 Null 值?
【发布时间】:2015-11-07 06:40:21
【问题描述】:

我正在使用 Glass V4。我有一个 MVC Web Area Project 的设置。

我已经在主项目 (WebProject) 中安装了 Glass Mapper。

我正在尝试在我的区域项目中进行玻璃铸造。

 public class ContactController : SitecoreController
{
    private readonly ISitecoreContext _context;
    private IGlassHtml _glassHtml;

    public ContactController()
        : this(new SitecoreContext())
    {

    }
    public ContactController(ISitecoreContext context)
    {
        _context = context;
        _glassHtml = new GlassHtml(context);

    }

    // GET: Contact
    public ActionResult ContactUs()
    {
        var db = Sitecore.Context.Database;
        var datasource = db.GetItem(RenderingContext.Current.Rendering.DataSource);

        var ViewModel = new Models.ContactUs();
        ViewModel.Headerstring = datasource.Fields["Headerstring"].Value;
        ViewModel.Substring = datasource.Fields["Substring"].Value;
        ViewModel.Description = ((MultilistField)datasource.Fields["Description"]).GetItems().Select(s => s.Fields["Line"].Value).ToList<string>();

        return View(ViewModel);
    }

    public ActionResult ContactUsGlass()
    {
        var model = _context.GetCurrentItem<ContactUsGlassModel>();
        return View(model);
    }
}

我能够使用第一个操作方法获得价值,但不能使用第二个。

型号:

public class ContactUs
{
    public string Headerstring { get; set; }
    public string Substring { get; set; }
    public List<string> Description { get; set; }
}

玻璃模型:

public class ContactUsGlassModel
{
    public virtual string Headerstring { get; set; }
    public virtual string Substring { get; set; }
}

我了解我不需要在 Glass V4 中注册我的命名空间。

【问题讨论】:

  • 您能否检查您的项目是否已发布以及是否有上下文语言版本?
  • @sitecoreclimber,是的。

标签: sitecore glass-mapper sitecore-mvc


【解决方案1】:

你不应该使用_context.GetCurrentItem 方法。请改用_context.GetItem

public ActionResult ContactUsGlass()
{
    var model = context.GetItem<ContactUsGlassModel>(RenderingContext.Current.Rendering.DataSource);
    return View(model);
}

您不想从 Sitecore.Context.Item 中获取模型(在 GetCurrentItem 方法中使用。您想从当前渲染的 DataSource 中获取模型。

【讨论】:

  • 我已经更新了代码,var model = _context.GetItem(RenderingContext.Current.Rendering.DataSource);但是现在由于 RenderingContext,我无法对代码进行单元测试。你能就此提出建议吗?
【解决方案2】:

@Marek 的回答是将渲染项拉入模型的正确方法。 GetCurrentItem 默认提供由 Sitecore 提供的页面项目。如果您的模型需要的字段是您的页面项的字段,那么 GetCurrentItem 也可以填充您的模型。如果启用了数据源嵌套,那么如果渲染时没有设置数据源,Sitecore 会再次返回页面项。

【讨论】:

  • @Sakthivel,您可以从 RenderingContext 类中提取一个 IRenderingContext 接口。为 IRenderingContext 创建一个 MVC 模型绑定器并注册它。我通常对大多数 Sitecore.Context 相关属性执行此模式。同样值得注意的是 GlassModelBinder 的这种模式。虽然方式不同,但我在我的解决方案中使用了类似的方法link
  • 当然也要试试这个...谢谢...!
【解决方案3】:

您可以从 GlassController 继承,然后使用 GetLayoutItem() 来获取 datasorced 项目。如果它为空,那么您需要在 sitecore 中发布模板,如果您不使用 TDS,请确保您的映射是正确的 :)

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    • 2022-12-26
    • 1970-01-01
    • 2013-10-07
    相关资源
    最近更新 更多