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”.
ASP.NET MVC 3 now supports DisplayAttribute in System.ComponentModel.DataAnnotation namespace. DisplayAttribute is new in .NET 4.
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”.
“DisplayNameAttribute” only supports a string which is the DisplayName.
Even though it doesn’t make sense to do so, what happens if we were to specify both attributes?
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.
Below is a simple example on how to configure the resources so they can be displayed based on the localization.
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.
Below is the usage of new sub classed attribute:
No comments:
Post a Comment