ASP.NET MVC 3 localization with DisplayAttribute and custom resource provider

slfan picture slfan · Feb 2, 2011 · Viewed 29.7k times · Source

I use a custom resource provider to get resource strings from a database. This works fine with ASP.NET where I can define the resource type as a string. The metadata attributes for model properties in MVC 3 (like [Range], [Display], [Required] require the type of a Resource as a parameter, where the ResourceType is the type of the generated code-behind class of a .resx file.

    [Display(Name = "Phone", ResourceType = typeof(MyResources))]
    public string Phone { get; set; }

Because I don't have .resx files, such a class does not exist. How can I use the model attributes with a custom resource provider?

I would like to have something like this:

    [Display(Name = "Telefon", ResourceTypeName = "MyResources")]
    public string Phone { get; set; }

The DisplayNameAttribute from System.ComponentModel had a overridable DisplayName Property for this purpose, but the DisplayAttribute class is sealed. For the validation attributes no corresponding classes exist.

Answer

Marcin Rybacki picture Marcin Rybacki · Feb 8, 2012

The most cleanest way I came up with is to override DataAnnotationsModelMetadataProvider. Here's a very neat article on how to do this.

http://buildstarted.com/2010/09/14/creating-your-own-modelmetadataprovider-to-handle-custom-attributes/