ASP.NET MVC4 Multi-lingual Data Annotations

10,465

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.

Share:
10,465
Paul Brown
Author by

Paul Brown

Updated on July 20, 2022

Comments

  • Paul Brown
    Paul Brown almost 2 years

    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).

  • Nathan
    Nathan over 2 years
    Does anybody have a similar solution like Phil Haack's for .NET Core 5.0 ?