2011-05-25 82 views
16

另一個MVC定位問題的整個列表...哪裏是默認的錯誤消息對DataAnnotations在MVC 3

我試圖使用本地化的資源文件中顯示的文本進行本地化的ASP.Net MVC 3應用程序意見,建議。

問題是,像往常一樣,試圖本地化數據註釋中的默認錯誤消息。

我知道你可以指定每個屬性的資源文件和密鑰:

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

,甚至,這是更好的首選,您可以覆蓋默認的消息,像這樣:Default resource for data annotations in ASP.NET MVC,這樣你就可以離開的屬性,如:

[Required] 
public string Username { get; set; } 

這最後一種方法是我在下面的一個,和它的作品,但只有當你想覆蓋DataAnnotation有一個且只有一個錯誤信息,因爲它總是會尋找一個資源鍵稱爲相同的屬性在自定義資源文件(例如, 「Required」需要資源文件中的「RequiredAttribute」條目)

其他屬性(如StringLength)具有多條錯誤消息,具體取決於您使用的可選參數。所以,如果你有這樣一個模型:

public class Person 
{ 
    [Required] 
    [StringLengthLocalizedAttribute(10, MinimumLength = 5)] 
    [Display(Name = "User name")] 
    public string UserName { get; set; } 
} 

的錯誤信息是「領域用戶名必須與的最小長度和的最大長度的字符串。 「

如果你改變了StringLength屬性到:

[StringLengthLocalizedAttribute(10)] 

錯誤信息更改爲「該字段用戶名稱必須是最大長度爲的字符串。「所以,在這種情況下,至少有2個默認錯誤信息覆蓋,並給出瞭解決方案@ KIM-tranjan失敗

我的部分解決方案,這是實現這樣我自己StringLength屬性:

public class StringLengthLocalizedAttribute : StringLengthAttribute 
{ 
    public StringLengthLocalizedAttribute(int maximumLength) : base(maximumLength) 
    { 
     ErrorMessageResourceType = typeof(CustomValidationResource); 
    } 

    public override string FormatErrorMessage(string name) 
    { 
     ErrorMessageResourceName = MinimumLength > 0 ? "StringLengthAttributeMinMax" : "StringLengthAttributeMax"; 
     return base.FormatErrorMessage(name); 
    } 
} 

如果我有一個本地化的資源「CustomValidationResource」利用有效信息,並將其設置爲ErrorMessageResourceType。然後,覆蓋FormatErrorMessage功能,我決定哪些消息字符串應適用取決於可選參數。

所以,這裏的問題是:是否有人k現在我們可以在哪裏找到DataAnnotation Attributes使用的所有資源鍵的列表,然後查看每個錯誤消息中有多少個不同的錯誤消息,而無需對每個錯誤消息進行測試?

甚至更​​好,我們可以讓原始的RESX文件看到字符串模板並使用相同的資源鍵本地化它們嗎?這樣,只更改ErrorMessageResourceType應該適用於所有DataAnnotations Attibutes,並且我不需要猜測將「{1}」或「{2}」放在我的本地化字符串中的位置。

感謝, 塞爾吉

+0

您現在可以訪問.NET官方存儲庫 - http://referencesource.microsoft.com/#System.ComponentModel.DataAnnotations/Resources/DataAnnotationsResources.Designer.cs – Bakudan 2016-06-08 11:09:07

回答

5

如果打開System.ComponentModel.DataAnnotations.dll用的工具,像反射,你可以打開資源System.ComponentModel.DataAnnotations.Resources.DataAnnotationsResources.resources看看吧。

您還可以查看提供對資源字符串的訪問權限的System.ComponentModel.DataAnnotations.Resources.DataAnnotationsResources類。

18

如果你還在尋找驗證字符串的概述,下面你可以從System.ComponentModel.DataAnnotations.Resources.DataAnnotationsResources類作爲Tz_提到的發現此次被資源:

[ArgumentIsNullOrWhitespace, The argument '{0}' cannot be null, empty or contain only white space.] 
[AssociatedMetadataTypeTypeDescriptor_MetadataTypeContainsUnknownProperties, The associated metadata type for type '{0}' contains the following unknown properties or fields: {1}. Please make sure that the names of these members match the names of the properties on the main type.] 
[AttributeStore_Type_Must_Be_Public, The type '{0}' must be public.] 
[AttributeStore_Unknown_Method, The type '{0}' does not contain a public method named '{1}'.] 
[AttributeStore_Unknown_Property, The type '{0}' does not contain a public property named '{1}'.] 
[Common_NullOrEmpty, Value cannot be null or empty.] 
[Common_PropertyNotFound, The property {0}.{1} could not be found.] 
[CompareAttribute_MustMatch, '{0}' and '{1}' do not match.] 
[CompareAttribute_UnknownProperty, Could not find a property named {0}.] 
[CreditCardAttribute_Invalid, The {0} field is not a valid credit card number.] 
[CustomValidationAttribute_Method_Must_Return_ValidationResult, The CustomValidationAttribute method '{0}' in type '{1}' must return System.ComponentModel.DataAnnotations.ValidationResult. Use System.ComponentModel.DataAnnotations.ValidationResult.Success to represent success.] 
[CustomValidationAttribute_Method_Not_Found, The CustomValidationAttribute method '{0}' does not exist in type '{1}' or is not public and static.] 
[CustomValidationAttribute_Method_Required, The CustomValidationAttribute.Method was not specified.] 
[CustomValidationAttribute_Method_Signature, The CustomValidationAttribute method '{0}' in type '{1}' must match the expected signature: public static ValidationResult {0}(object value, ValidationContext context). The value can be strongly typed. The ValidationContext parameter is optional.] 
[CustomValidationAttribute_Type_Conversion_Failed, Could not convert the value of type '{0}' to '{1}' as expected by method {2}.{3}.] 
[CustomValidationAttribute_Type_Must_Be_Public, The custom validation type '{0}' must be public.] 
[CustomValidationAttribute_ValidationError, {0} is not valid.] 
[CustomValidationAttribute_ValidatorType_Required, The CustomValidationAttribute.ValidatorType was not specified.] 
[DataTypeAttribute_EmptyDataTypeString, The custom DataType string cannot be null or empty.] 
[DisplayAttribute_PropertyNotSet, The {0} property has not been set. Use the {1} method to get the value.] 
[EmailAddressAttribute_Invalid, The {0} field is not a valid e-mail address.] 
[EnumDataTypeAttribute_TypeCannotBeNull, The type provided for EnumDataTypeAttribute cannot be null.] 
[EnumDataTypeAttribute_TypeNeedsToBeAnEnum, The type '{0}' needs to represent an enumeration type.] 
[FileExtensionsAttribute_Invalid, The {0} field only accepts files with the following extensions: {1}] 
[LocalizableString_LocalizationFailed, Cannot retrieve property '{0}' because localization failed. Type '{1}' is not public or does not contain a public static string property with the name '{2}'.] 
[MaxLengthAttribute_InvalidMaxLength, MaxLengthAttribute must have a Length value that is greater than zero. Use MaxLength() without parameters to indicate that the string or array can have the maximum allowable length.] 
[MaxLengthAttribute_ValidationError, The field {0} must be a string or array type with a maximum length of '{1}'.] 
[MetadataTypeAttribute_TypeCannotBeNull, MetadataClassType cannot be null.] 
[MinLengthAttribute_InvalidMinLength, MinLengthAttribute must have a Length value that is zero or greater.] 
[MinLengthAttribute_ValidationError, The field {0} must be a string or array type with a minimum length of '{1}'.] 
[PhoneAttribute_Invalid, The {0} field is not a valid phone number.] 
[RangeAttribute_ArbitraryTypeNotIComparable, The type {0} must implement {1}.] 
[RangeAttribute_MinGreaterThanMax, The maximum value '{0}' must be greater than or equal to the minimum value '{1}'.] 
[RangeAttribute_Must_Set_Min_And_Max, The minimum and maximum values must be set.] 
[RangeAttribute_Must_Set_Operand_Type, The OperandType must be set when strings are used for minimum and maximum values.] 
[RangeAttribute_ValidationError, The field {0} must be between {1} and {2}.] 
[RegexAttribute_ValidationError, The field {0} must match the regular expression '{1}'.] 
[RegularExpressionAttribute_Empty_Pattern, The pattern must be set to a valid regular expression.] 
[RequiredAttribute_ValidationError, The {0} field is required.] 
[StringLengthAttribute_InvalidMaxLength, The maximum length must be a nonnegative integer.] 
[StringLengthAttribute_ValidationError, The field {0} must be a string with a maximum length of {1}.] 
[StringLengthAttribute_ValidationErrorIncludingMinimum, The field {0} must be a string with a minimum length of {2} and a maximum length of {1}.] 
[UIHintImplementation_ControlParameterKeyIsNotAString, The key parameter at position {0} with value '{1}' is not a string. Every key control parameter must be a string.] 
[UIHintImplementation_ControlParameterKeyIsNull, The key parameter at position {0} is null. Every key control parameter must be a string.] 
[UIHintImplementation_ControlParameterKeyOccursMoreThanOnce, The key parameter at position {0} with value '{1}' occurs more than once.] 
[UIHintImplementation_NeedEvenNumberOfControlParameters, The number of control parameters must be even.] 
[UrlAttribute_Invalid, The {0} field is not a valid fully-qualified http, https, or ftp URL.] 
[ValidationAttribute_Cannot_Set_ErrorMessage_And_Resource, Either ErrorMessageString or ErrorMessageResourceName must be set, but not both.] 
[ValidationAttribute_IsValid_NotImplemented, IsValid(object value) has not been implemented by this class. The preferred entry point is GetValidationResult() and classes should override IsValid(object value, ValidationContext context).] 
[ValidationAttribute_NeedBothResourceTypeAndResourceName, Both ErrorMessageResourceType and ErrorMessageResourceName need to be set on this attribute.] 
[ValidationAttribute_ResourcePropertyNotStringType, The property '{0}' on resource type '{1}' is not a string type.] 
[ValidationAttribute_ResourceTypeDoesNotHaveProperty, The resource type '{0}' does not have an accessible static property named '{1}'.] 
[ValidationAttribute_ValidationError, The field {0} is invalid.] 
[ValidationContext_Must_Be_Method, The ValidationContext for the type '{0}', member name '{1}' must provide the MethodInfo.] 
[ValidationContextServiceContainer_ItemAlreadyExists, A service of type '{0}' already exists in the container.] 
[Validator_InstanceMustMatchValidationContextInstance, The instance provided must match the ObjectInstance on the ValidationContext supplied.] 
[Validator_Property_Value_Wrong_Type, The value for property '{0}' must be of type '{1}'.] 

(MVC 4,.NET 4.0)

+0

你是如何得到這個列表的? – roydukkey 2016-02-06 19:31:58

+0

尋找源反射器 – juFo 2016-02-08 12:53:43

+0

對不起。有沒有教程或源代碼? – roydukkey 2016-02-08 13:37:08

相關問題