Search code examples
c#.netasp.net-mvcdata-annotationsmultilingual

ASP.NET MVC4 Multi-lingual Data Annotations


In a standard application I have the following:

[Required]
[DisplayName("Email Address")]
public string EmailAddress { get; set; }

...this in turn generates a label for this form field automatically in English.

Now, if I need my app to support 5 languages, what is the best approach from a ASP.NET MVC application to handle this?

Scope of application is about 400 - 600 data fields.

UPDATE: I will also require support for updating small sections of text in the application like page names and introductions to each form (small paragraph).


Solution

  • Instead of assigning the actual values to the attribute properties, assign keys for resource strings. Then, you can use a custom ModelMetadataProvider that is aware of the localization context and will provide the appropriate string. To get a better solution, you can make your custom ModelMetadataProvider infer conventions, (which cuts down on the need for verbose attributes).

    Phil Haack has a blog article called Model Metadata and Validation Localization using Conventions that explains how this works. There is also a corresponding NuGet package called ModelMetadataExtensions with source code available on github at https://github.com/Haacked/mvc-metadata-conventions .

    As a side note, I'd recommend reviewing some of the awesome answers I got on an old question of mine: Effective Strategies for Localization in .NET. They don't specifically address your question, but will be very helpful if you are working on a multilingual .NET app.