开发者

MVC Data annotation in different languages?

I'm using code like this:

   @Html.LabelFor(m => m.Login.Password, new { @class = "adm" })
   @Html.PasswordFor(m => m.Login.Password, new { @class = "adm", size = 30 })
   @Html.ValidationMessageFor(m => m.Login.Password)

It works fine as my data annotations/messages/labels are all in Englis开发者_StackOverflowh. However is there some way I can have more than one language and switch between them?

What if my site has a language selector that selects between Japanese and English? Can I have different data annotation for each language?


1> You need to create a resource file for each language

2> then create models like

public class User
{
    [Required(ErrorMessageResourceType=typeof(Languages.Resource),ErrorMessageResourceName="required")]
    [Display(ResourceType=typeof(Languages.Resource),Name="name")]
    public string Name { get; set; }

}

3> Your views are okie

4> To choose and set different languages: you may create a drown menu (or whatever you want) and then on server , store the chosen language in a cookie. And for each request set current_culture_info as below

    string currentChoosenLanguage= readFromCookie(); //or may be from Database, whatever suits you
    CultureInfo ci = new CultureInfo(currentChoosenLanguage); //i think jp: for japanese
    System.Threading.Thread.CurrentThread.CurrentUICulture = ci;
    Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);

please check below link

http://haacked.com/archive/2011/07/14/model-metadata-and-validation-localization-using-conventions.aspx/


You will have to use Globalization/Localization,

You can add resourcenames to your error messages.

For example:

[Required(ErrorMessageResourceName= "PasswordRequired", ErrorMessageResourceType = typeof(MyResource)]

I suggest your look up some more information about the resources files for Globalization/localization

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜