【问题标题】:Get Label for Expresssion Func<T, U> Only Works for String Type获取表达式 Func<T, U> 的标签仅适用于字符串类型
【发布时间】:2014-05-31 07:28:43
【问题描述】:

我有一个函数,它需要一个 Expression>,我想从模型中的元数据中获取 DisplayName。这仅适用于具有 Func 签名的表达式。 FuncFunc 失败并出现以下错误。

模板只能用于字段访问、属性访问、一维数组索引或单参数自定义索引器表达式。

具有一些属性的示例元数据类

这是一个示例 元数据 类,它为一些属性提供 DisplayAttribute

public class TestMetadata
{
    [Display(Name = "Area")]
    public Object Description { get; set; }

    [Display(Name = "Date Property")]
    public Object Date { get; set; }

    [Display(Name = "Int Property")]
    public Object Length { get; set; }
}

提取显示属性名称属性的函数

此函数适用于字符串的返回值(示例 CustomDisplayFor(Html,m => m.Description) 按预期返回值“Area”)。但是,在以下情况下失败并显示错误。

public static String CustomDisplayFor<TModel>(HtmlHelper<TModel> html,
    Expression<Func<TModel, Object>> func) 
{ 
   return html.LabelFor(func);
}

有没有办法从这些其他类型的属性中获取 DisplayAttribute 信息?

【问题讨论】:

    标签: asp.net-mvc entity-framework metadata html-helper func


    【解决方案1】:

    好的,我发现当您为返回值添加另一个类型引用时,这会起作用。

    签名变成

    public static String CustomDisplayFor<TModel,TResult>(HtmlHelper<TModel> html,
        Expression<Func<TModel, TResult>> func) 
    { 
       return html.LabelFor(func);
    }
    

    调用代码是一样的

    CustomDisplayFor(Html,m => m.Date) // This now works => "Date Property" returned
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-07
      • 1970-01-01
      • 2017-05-15
      • 1970-01-01
      • 2011-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多