【问题标题】:How can I get the sitecore field from an object property, mapped by glassmapper?如何从由 glassmapper 映射的对象属性中获取 sitecore 字段?
【发布时间】:2014-09-02 14:40:32
【问题描述】:

我们将 Glass Mapper 与 Sitecore 结合使用,通过我们的模型,我们可以获取 sitecore 字段的值。但是我想通过使用模型轻松获取站点核心字段(站点核心字段类型),而不将任何字符串(使用GetProperty()时,您需要属性名称字符串)硬编码到方法中。

所以我写了这个东西来实现这一点,但是我不满意使用它时需要传入 2 种类型,因为当你有一个长模型标识符时它看起来很糟糕。

   public static string SitecoreFieldName<T, TU>(Expression<Func<TU>> expr)
    {
         var body = ((MemberExpression)expr.Body);
         var attribute = (typeof(T).GetProperty(body.Member.Name).GetCustomAttributes(typeof(SitecoreFieldAttribute), false)[0]) as SitecoreFieldAttribute;
         return attribute.FieldName;
    }

最理想的方式是能够像Model.SomeProperty.SitecoreField()这样得到它。但是我不知道如何从那里进行反射。因为这可以是任何类型的扩展。

谢谢!

【问题讨论】:

  • 我知道我应该检查空数组。所以忽略这个。
  • 那么你的问题是什么?对我来说看起来很简单和通用..
  • 问题是进一步改进它。在这种情况下,您需要传入 2 种类型才能使其工作,当您在数据绑定上下文中使用它时,在 aspx 页面上看起来不太好。

标签: c# sitecore glass-mapper


【解决方案1】:
public static string SitecoreFieldName<TModel>(Expression<Func<TModel, object>> field)
{
    var body = field.Body as MemberExpression;

    if (body == null)
    {
        return null;
    }

    var attribute = typeof(TModel).GetProperty(body.Member.Name)
        .GetCustomAttributes(typeof(SitecoreFieldAttribute), true)
        .FirstOrDefault() as SitecoreFieldAttribute;

    return attribute != null
        ? attribute.FieldName
        : null;
}

请注意,我将 inherit=true 放在了 GetCustomAttributes 方法调用上。
否则继承的属性将被忽略。

【讨论】:

  • 对不起,我还不能投票,但谢谢!这正是我想要的。
【解决方案2】:

我不明白为什么我的问题被否决了。所以你认为它已经是完美的代码了吗?

在另一位资深开发者的帮助下,我今天对其进行了改进,使其不再需要 2 种类型,并且使用语法更加清晰:

public static Field GetSitecoreField<T>(T model, Expression<Func<T, object>> expression) where T : ModelBase
    {
        var body = ((MemberExpression)expression.Body);
        var attributes = typeof(T).GetProperty(body.Member.Name).GetCustomAttributes(typeof(SitecoreFieldAttribute), false);
        if (attributes.Any())
        {
            var attribute = attributes[0] as SitecoreFieldAttribute;
            if (attribute != null)
            {
                return model.Item.Fields[attribute.FieldName];
            }
        }
        return null;
    }

我可以通过这样做来调用它:

GetSitecoreField(Container.Model<SomeModel>(), x => x.anyField)

希望它能帮助任何将 Glass Mapper 与 Sitecore 一起使用并希望从模型属性中获取当前 sitecore 字段的人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    • 2011-01-27
    相关资源
    最近更新 更多