我正在使用System.ComponontModel.DataAnnotations來驗證我的模型對象。我怎樣才能替代消息的標準屬性(必需和StringLength)產生,而不提供ErrorMessage屬性給每個人或子類他們?如何替換標準DataAnnotations錯誤消息
回答
寫新帖,因爲我需要更多的格式比評論提供。
看ValidationAttribute - 驗證屬性的基類。
如果驗證出錯,錯誤信息將被方法創建:
public virtual string FormatErrorMessage(string name)
{
return string.Format(CultureInfo.CurrentCulture, this.ErrorMessageString, new object[] { name });
}
接下來看看ErrorMessageString屬性:
:protected string ErrorMessageString
{
get
{
if (this._resourceModeAccessorIncomplete)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, DataAnnotationsResources.ValidationAttribute_NeedBothResourceTypeAndResourceName, new object[0]));
}
return this.ResourceAccessor();
}
}
物業ResourceAccessor可以從設置好的
ValidationAttribute..ctor(Func<String>)
ValidationAttribute.set_ErrorMessage(String) : Void
ValidationAttribute.SetResourceAccessorByPropertyLookup() : Void
首先是被dervided類正確使用的格式化消息,第二個 - 當我們設置錯誤消息槽ErrorMessage屬性的情況,以及第三 - 當使用資源字符串時。 根據您的情況,您可以使用ErrorMessageResourceName。
其他方面讓我們來看看衍生構造,對於我們的例子,範圍屬性:
internal static string RangeAttribute_ValidationError
{
get
{
return ResourceManager.GetString("RangeAttribute_ValidationError", resourceCulture);
}
}
所以,你可以創建不同的棕褐色的資源文件:
private RangeAttribute()
: base((Func<string>) (() => DataAnnotationsResources.RangeAttribute_ValidationError))
{
}
這裏RangeAttribute_ValidationError從資源加載默認文化和覆蓋消息,如下所示:
http://www.codeproject.com/KB/aspnet/SatelliteAssemblies.aspx
http://msdn.microsoft.com/en-us/library/aa645513(VS.71).aspx
您可以使用的ErrorMessage基類ValidationAttribute的財產所有DataAnnotations驗證。
例如:
[Range(0, 100, ErrorMessage = "Value for {0} must be between {1} and {2}")]
public int id;
也許這會幫助你。
是的。但是有沒有辦法一次替換默認信息? – 2010-02-07 22:54:34
@FitzchakYitzchaki你有沒有達到過? – 2016-07-11 13:52:22
- 1. 如何使用標準錯誤消息
- 2. 標準錯誤消息
- 3. 如何更換標準錯誤信息?
- 4. 如何在Codeigniter中自行更換標準錯誤消息?
- 5. MVC DataAnnotations除去錯誤消息
- 6. 如何將錯誤消息打印到標準錯誤?
- 7. 如何用我定義的錯誤消息替換Linux內核錯誤消息?
- 8. 如何用錯誤頁面替換錯誤消息
- 9. 更改h:message JSF標準錯誤消息
- 10. 標準django表單錯誤消息
- 11. 顯示標準錯誤消息
- 12. 用自定義消息替換錯誤
- 13. 進程替換捕獲標準錯誤
- 14. 如何用彈出窗口(WIX)替換錯誤消息(2753)
- 15. 如何在表單驗證中替換錯誤消息
- 16. VBA:如何顯示錯誤消息,就像標準錯誤消息有一個「調試」按鈕?
- 17. 錯誤信息標準錯誤Shellscript
- 18. DataAnnotations無效值的消息
- 19. 哪裏是默認的錯誤消息對DataAnnotations在MVC 3
- 20. flex錯誤消息標籤
- 21. 如何替換.NET標準的System.ComponentModel.DataAnnotations類?
- 22. 如何用PureMVC MultiCore替換PureMVC標準
- 23. 錯誤消息錯誤:下標出界
- 24. 發送消息時,Sendgrid SMTP API不會替換替換標記
- 25. 構建標準化的異常/錯誤消息集合
- 26. Zend Framework 2 - 翻譯標準表單驗證和錯誤消息
- 27. 刪除ALV網格中檢查表的標準錯誤消息
- 28. 是否有錯誤消息的行業標準?
- 29. Phalcon:顯示花哨錯誤消息而不是標準異常
- 30. 瞭解C出口()和標準錯誤消息的行爲
非常感謝Veton。你提到的最後一部分我完全錯過了。 – 2010-02-09 11:52:04
我無法理解資源文件應該如何命名(以及放置在何處)從DataAnnotations.dll覆蓋ResourceManager。 – wRAR 2010-03-17 15:03:03