从编辑器模板内访问自定义属性

Bra*_*die 5 c# asp.net-mvc razor asp.net-mvc-4

是否可以从该属性的编辑器模板中访问该属性的自定义属性?

例如,我有一个带有自定义属性的简单类:

public class MyClass
{
   [MyCustomAttribute("myCustomValue")]
   public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后我有一个编辑器模板string,我想检查字符串属性是否具有该自定义属性。

我尝试过从视图访问类型CustomAttributes,但是当模型的实例为空时,这将不起作用。

Bra*_*die 6

我在编辑器模板中使用以下代码从属性中获取属性值

var Member = ViewData.ModelMetadata.ContainerType.GetMember(ViewData.ModelMetadata.PropertyName);
var Attribute = Member[0].GetCustomAttribute<MyCustomAttribute>();
if(Attribute != null)
{
    <p>@Attribute.MyProperty</p>
} 
Run Code Online (Sandbox Code Playgroud)

代码有点粗糙并做出了一些假设,但您已经了解了总体思路。