2010-09-21 21 views
20

如果我裝飾我的ViewModels的屬性,像這樣的屬性:本地化數據註釋缺省消息([必需] [StringLength]等)

public class Vm 
{ 

[Required] 
[StringLength(35)] 
public string Name {get;set;} 

} 

我會得到英語驗證消息:

"this field is required" 
"The field Name must be a string with a maximum length of 35" 

我怎麼翻譯它們?

+0

我這裏介紹我的方法: http://stackoverflow.com/questions/19398691/ mvc-localization-from-the-database-that-c​​overs-all-messages-required-displayna – 2013-10-16 08:37:56

回答

36

您可以使用ErrorMessageResourceName屬性:

[Required(ErrorMessageResourceName = "SomeResource")] 
[StringLength(30, ErrorMessageResourceName = "SomeOtherResource")] 
public string Name { get; set; } 

您可以籤this blog post爲例。


UPDATE:

Application_Start

DefaultModelBinder.ResourceClassKey = "Messages"; 

而在Messages.resx文件,你需要添加自定義錯誤消息。使用反射器查看System.Web.MvcSystem.ComponentModel.DataAnnotations程序集以查看要使用的鍵名稱。

+2

我願意可以更改默認消息,而不必爲每個屬性指定默認消息,我看到一次必須在App_GlobalResources中具有Messages.resx,但我不知道每條消息的密鑰 – Omu 2010-09-21 08:43:58

+0

請查看我的更新。 – 2010-09-21 08:48:24

+0

@Darin Dimitrov能否請你告訴我更確切地在System.Web.Mvc中看看 – Omu 2010-09-21 10:02:35

9

現在有一個更好的解決方案,使用asp.net MVC 3,目前有人正在尋找一種更新,更好的方法。

http://blog.gauffin.org/2011/09/easy-model-and-validation-localization-in-asp-net-mvc3/

例如:

public class UserViewModel 
{ 
    [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Resources.LocalizedStrings))] 
    [LocalizedDisplayName(ErrorMessageResourceName = "UserId", ErrorMessageResourceType = typeof(Resources.LocalizedStrings))] 
    [LocalizedDescription(ErrorMessageResourceName = "UserIdDescription", ErrorMessageResourceType = typeof(Resources.LocalizedStrings))] 
    public int Id { get; set; } 
} 

SO相關的問題 - Mvc 3.0 DataAnnotations Localization

+0

下來選民,請解釋你的行動的理由。 – 2013-11-02 18:48:46

相關問題