从编辑器模板中的自定义属性获取值

时间:2010-09-30 08:31:52

标签: asp.net-mvc asp.net-mvc-2 editortemplates

目前我有这个:

ViewModel中的

[MyCustom(Foo = 23)]
public int CountryId { get; set; }
编辑器模板中的

<%= Html.TextBox("", Model) %>

如何从我的自定义属性(MyCustom)中获取值(Foo = 23)到编辑器模板中?

1 个答案:

答案 0 :(得分:10)

在编辑器模板中,您可以获得自定义属性的值,如下所示。

@model int

@{       
    var CustomAttributes = (ViewData.ModelMetadata).ContainerType.GetProperty(ViewData.ModelMetadata.PropertyName).GetCustomAttributes(typeof(MvcApplication7.Models.MyCustomAttribute), false);
    if (CustomAttributes.Length > 0)
    {
        MvcApplication7.Models.MyCustomAttribute CustomAttribute = CustomAttributes[0] as MvcApplication7.Models.MyCustomAttribute;

        //That is how you get the value of foo. You can use it as per need of the editor template.
        @CustomAttribute.Foo   
    }
}