2010-02-27 120 views
24

我正在用C#構建一個MVC Web應用程序。由於該網站將是多語言的,我已經實現了我自己的ResourceManager。這個類負責根據當前的線程文化從數據庫/緩存中獲取所需的資源字符串,並且工作良好。如何使用DataAnnotations ErrorMessageResourceName與自定義資源解決方案

我的問題是,我想使用我自定義的ResourceManager解決方案來獲取驗證錯誤消息,例如在屬性上使用必需的屬性。這可以做到嗎?

回答

49

RequiredAttribute允許使用custom resource manager

[Required(
    ErrorMessageResourceType = typeof(CustomResourceManager), 
    ErrorMessageResourceName = "ResourceKey")] 
public string Username { get; set; } 

UPDATE:

另一種可能性是編寫自定義屬性:

public class CustomRequiredAttribute : RequiredAttribute 
{ 
    public override string FormatErrorMessage(string name) 
    { 
     return YourCustomResourceManager.GetResource(name); 
    } 
} 
+1

我的ResourceManager是一個真正的定製解決方案並沒有以任何方式連接到MVC,也沒有實現除t之外的任何接口他是我創造的一個。需要進行哪些更改才能以這種方式使用我的ResourceHandler? – Mats 2010-02-27 15:49:21

+0

請參閱我的更新。 – 2010-02-27 15:54:05

+0

是否需要其他東西才能使自定義屬性起作用?我試過這個,但它似乎不工作。我是否需要創建自己的EditorFor擴展方法來使用新的屬性類型? – 2013-10-26 03:33:08

相關問題