【问题标题】:MVC 5 using Attributes on Object to drive HtmlHelper unable to readMVC 5 使用对象上的属性来驱动 HtmlHelper 无法读取
【发布时间】:2015-12-19 22:42:17
【问题描述】:

我有一个对象:具有多个属性(品牌、型号和颜色)的汽车。每个属性都有一个分配的属性 (BilingualLabel)。

我正在尝试为分配有 BilingualLabel 属性的任何类型编写强类型 htmlhelper。 IE。我想获取我归因于 Car 类中的属性的“MakeFR”文本。

例如

[System.AttributeUsage(AttributeTargets.Property)]
public class BilingualLabel : System.Attribute
{
    private string _resourceCode = "";

    public BilingualLabel(string ResourceCode)
    {
        _resourceCode = ResourceCode;
    }
}

然后是汽车类:

public class Car
{
    [BilingualLabel("MakeFR")]
    public string Make { get; set; }

    [BilingualLabel("ModelFR")]
    public string Model { get; set; }

    [BilingualLabel("ColorFR")]
    public string Color { get; set; }

}

现在我来到帮助类,我似乎无法获得我设置的属性值。我已经展示了我尝试过的两种尝试。它们都作为空属性返回。

    public static MvcHtmlString BilingualLabelFor<T,E>(this HtmlHelper<T> htmlHelper, Expression<Func<T,E>> expression)
    {

        //get the Bilingual Label resource code

        //BilingualLabel attr =
        //    (BilingualLabel)Attribute.GetCustomAttribute(typeof(E), typeof(BilingualLabel));

        MemberExpression member = expression.Body as MemberExpression;
        PropertyInfo propInfo = member.Member as PropertyInfo;


        MvcHtmlString html = default(MvcHtmlString);

        return html;
    }

【问题讨论】:

  • 您的资源是静态的吗?可以使用localization 的内置功能吗?

标签: asp.net-mvc model-view-controller html-helper custom-attributes


【解决方案1】:

现在,您的 GetCustomAttribute 调用正在尝试从 typeof(E) 中获取 BilingualLabel,在您的情况下这将是一个字符串。您需要根据实际成员而不是类型来获取自定义属性。此外,如果您想从自定义属性中取回设置的值,则需要将其设置为公共属性。

更新属性以拥有公共属性:

[System.AttributeUsage(AttributeTargets.Property)]
public class BilingualLabel : System.Attribute
{
    public string ResourceCode { get; private set; }

    public BilingualLabel(string resourceCode)
    {
        this.ResourceCode = resourceCode;
    }
}

然后将 GetCustomAttribute 拉出成员而不是类型:

public static MvcHtmlString BilingualLabelFor<T,E>(this HtmlHelper<T> htmlHelper, Expression<Func<T,E>> expression)
{

    MvcHtmlString html = default(MvcHtmlString);

    MemberExpression memberExpression = expression.Body as MemberExpression;
    BilingualLabel attr = memberExpression.Member.GetCustomAttribute<BilingualLabel>();

    if (attr != null)
    {
      //Replace with actual lookup code to get Bilingual Label using attr.ResourceCode
      html = new MvcHtmlString(attr.ResourceCode);
    }

    return html;
}

【讨论】:

  • 您先生一定很难让您庞大的大脑通过门口。一个非常好的答案,我谢谢你。
猜你喜欢
  • 2023-03-31
  • 2018-11-08
  • 1970-01-01
  • 2019-06-08
  • 2015-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
相关资源
最近更新 更多