tags:

views:

16

answers:

1

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/DisplayTemplates/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!

+2  A: 

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