开发者

How do attributes work in MVC2

开发者 https://www.devze.com 2023-01-17 16:06 出处:网络
I\'m trying to work out exactly what role the attributes play when used on model properties. For example, If I have a Customer model with a display name attribute set on one of the properties, then I

I'm trying to work out exactly what role the attributes play when used on model properties.

For example, If I have a Customer model with a display name attribute set on one of the properties, then I can access the display name attribute value within a display template for whatever reason.

public class Customer {

        [DisplayName("Customer Name")]
        public string Name { get; set; }
    }

/Shared/DisplayTemplates/String.ascx <--- Uses this

<p><%=Model %> | <%=ViewData.ModelMetadata.DisplayName %></p>

-

If however I change the DisplayName attribute to DataType, then MVC looks for a template also called ImageUrl.

public class Customer {
        [DataType(DataType.ImageUrl)]
        public string Name { get; set; }
    }

/Shared/Dis开发者_StackOverflowplayTemplates/ImageUrl.ascx <---Uses this

<img href="<%=Model %>" /> | <%=ViewData.ModelMetadata.DisplayName %>

Why is the String template being ignored? I thought that MVC matches up the datatypes of the properties to the template names (like the first example) and the attributes are used as metadata within the templates.

It's all very confusing!


MVC matches the datatype of the property when looking for a template - as in your first example.

In your second example, your [DataType] attribute has overriden the string definition, so it now looks for a template named the same as the data type.

If you want to specify which template a property will use you can use the UIHint attribute

public class Customer {
        [UIHint("string")]
        [DataType(DataType.ImageUrl)]
        public string Name { get; set; }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消