简体   繁体   中英

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

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.

I would make custom attribute, like [MyDisplayName("Section", "Key")] And this would provide translation based on selected language. Also check out database driven resources manager, like http://www.west-wind.com/presentations/wwDbResourceProvider/

The best approach for localization is to store your strings in the database and not resource files unless,

  1. Your app is very static
  2. Your language set is very static

You can decorate your model with custom attribute where you set default string and DB id for the resource eg

[MyResource("email", 123)]

You can write custom http delegating handler to get resource out of cache (for example). Once you authenticate client, you know client's language demand and resource id. So, the client with Spanish and resource id = 1 will get "Si", the one with English will get "Yes". The resource id will be mapped to language-specific string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM