Asp.net-mvc – ASP.NET MVC 3 localization with DisplayAttribute and custom resource provider

asp.net-mvcasp.net-mvc-3displayattributeinternationalizationlocalization

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.

Best Answer

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/