Get Label for Expresssion Func<T, U> Only Works for String Type

I have a function that takes an Expression< Func < TModel, Object >> which I want to get the DisplayName from the metadata in the model. This works only for expressions with a signature of having Func< TModel,String> . Func< TModel,Int> or Func< TModel,DateTime> fails with the following error.

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

Example Metadata Class with a few properties

This is a sample Metadata class that supplies the DisplayAttribute for a few properties.

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; }
}

Function to Extract DisplayAttribute Name Property

This function works fine for the return values of string (Example CustomDisplayFor(Html,m => m.Description) returns the value "Area" as expected). However, fails with the noted error in the following circumstances.

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

Is there a way I can get the DisplayAttribute information from these other types of properties?


Okay, I figured out that this works when you add another Type Reference for the return value.

The Signature Becomes

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

Calling Code is the Same

CustomDisplayFor(Html,m => m.Date) // This now works => "Date Property" returned
链接地址: http://www.djcxy.com/p/19086.html

上一篇: 5:显示完整名称

下一篇: 为Expresssion Func <T,U>获取标签仅适用于字符串类型