Thursday, July 28, 2016

The difference between DisplayNameAttribute and MVC 3 new DisplayAttribute


You may already know that ASP.NET MVC 2 introduced the DisplayNameAttribute which is part of the System.ComponentModel namespace. This attribute allowed us to display the name of the customer as the “Customer Name” instead of the actual property name: “Name”.
mvc display name attribute
ASP.NET MVC 3 now supports DisplayAttribute in System.ComponentModel.DataAnnotation namespace. DisplayAttribute is new in .NET 4.
mvc display attribute
So what is the real difference between the “DisplayAttribute”, and the “DisplayNameAttribute”? They serve the same purpose, which is displaying a custom string, however the key difference is in the overloads they provide.
“DisplayAttribute” supports more overloads than the DisplayNameAttribute”.
display attribute param overload
DisplayNameAttribute” only supports a string which is the DisplayName.
display-name-attribute-param
Even though it doesn’t make sense to do so, what happens if we were to specify both attributes?
mvc display & display name attribute
In this situation, the new DisplayAttribute takes precedence over the DisplayNameAttribute. Instead of the “Customer name 2” we should see the “Customer name 1” displayed to the user.
Handing Resources
In some cases, we need the DisplayAttribute to be resource sensitive. For an example, instead of using non-localized resources, we might want to use the standard .NET resource provider to retrieve the localized resources. 
display-attribute
Below is a simple example on how to configure the resources so they can be displayed based on the localization.
resource-handling
image
As we did for the above DisplayAttribute, it is not straightforward to make DisplayNameAttribute to be resource sensitive. DisplayNameAttribute does not support a parameter for ResourceType. In that case, we need to subclass the DisplayNameAttribute and provide our own implementation similar to below.
image
Below is the usage of new sub classed attribute:
image




No comments: