在ASP.Net MVC 2中为非属性模型验证提供本地化错误消息?

时间:2010-03-19 21:01:01

标签: asp.net-mvc localization data-annotations

我正在使用DataAnnotations属性和ASP.Net MVC 2为我的ViewModel提供模型验证:

public class ExamplePersonViewModel {
    [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Resources.Validation))]
    [StringLength(128, ErrorMessageResourceName = "StringLength", ErrorMessageResourceType = typeof(Resources.Validation))]
    [DataType(DataType.Text)]
    public string Name { get; set; }

    [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Resources.Validation))]
    [DataType(DataType.Text)]
    public int Age { get; set; }
}

这似乎按预期工作(虽然它非常冗长)。我遇到的问题是,正在执行的幕后模型验证与任何特定属性无关。上述模型中的一个示例是Age属性需要是int。如果您尝试在表单上输入非整数值,则会出现以下(非本地化)消息时出错:

  

字段年龄必须是数字。

如何对这些非属性验证消息进行本地化?

是否有完整的这些消息列表,以便我确保它们都已本地化?

3 个答案:

答案 0 :(得分:18)

转到http://forums.asp.net/p/1512140/3608427.aspx,观看日期为01-09-2010,6:20的bradwils消息。

该解决方案对我有用。

知道可覆盖的消息的完整列表应该很有趣......

<强>更新

这里的帖子内容:

  

在App_GlobalResources中创建一个全局资源类,并将DefaultModelBinder.ResourceClassKey设置为此类的名称(例如,如果您创建了“Messages.resx”,则将ResourceClassKey设置为“Messages”)。

     

您可以在MVC 2中覆盖两个字符串:

     
      
  • 当用户输入的数据与数据类型不兼容时(例如,为整数字段键入“abc”),将使用“PropertyValueInvalid”的字符串值。默认消息是:“值”{0}“对{1}无效。”
  •   
  • 当用户未输入不可为空的字段的任何数据时(例如,整数字段),将使用“PropertyValueRequired”的字符串值。默认消息是:“需要值。”
  •   
     

在第二种情况下需要注意的是,如果您的验证器提供程序列表中有DataAnnotationsModelValidatorProvider(默认情况下是这样),那么您将永远不会看到第二条消息。此提供程序会看到非可选字段,并为它们添加隐含的[Required]属性,以便它们的消息与具有显式[Required]属性的其他字段保持一致,并确保您获得所需字段的客户端验证。

答案 1 :(得分:7)

消息列表(MVC 3.0):

ActionMethodSelector_AmbiguousMatch
ActionMethodSelector_AmbiguousMatchType
AsyncActionMethodSelector_AmbiguousMethodMatch
AsyncActionMethodSelector_CouldNotFindMethod
AsyncCommon_AsyncResultAlreadyConsumed
AsyncCommon_ControllerMustImplementIAsyncManagerContainer
AsyncCommon_InvalidAsyncResult
AsyncCommon_InvalidTimeout
AuthorizeAttribute_CannotUseWithinChildActionCache
ChildActionOnlyAttribute_MustBeInChildRequest
ClientDataTypeModelValidatorProvider_FieldMustBeNumeric
Common_NoRouteMatched
Common_NullOrEmpty
Common_PartialViewNotFound
Common_PropertyCannotBeNullOrEmpty
Common_PropertyNotFound
Common_TriState_False
Common_TriState_NotSet
Common_TriState_True
Common_TypeMustDriveFromType
Common_ValueNotValidForProperty
Common_ViewNotFound
CompareAttribute_MustMatch
CompareAttribute_UnknownProperty
Controller_UnknownAction
Controller_UpdateModel_UpdateUnsuccessful
Controller_Validate_ValidationFailed
ControllerBase_CannotExecuteWithNullHttpContext
ControllerBase_CannotHandleMultipleRequests
ControllerBuilder_ErrorCreatingControllerFactory
ControllerBuilder_FactoryReturnedNull
ControllerBuilder_MissingIControllerFactory
CshtmlView_ViewCouldNotBeCreated
CshtmlView_WrongViewBase
DataAnnotationsModelMetadataProvider_UnknownProperty
DataAnnotationsModelMetadataProvider_UnreadableProperty
DataAnnotationsModelValidatorProvider_ConstructorRequirements
DataAnnotationsModelValidatorProvider_ValidatableConstructorRequirements
DefaultControllerFactory_ControllerNameAmbiguous_WithoutRouteUrl
DefaultControllerFactory_ControllerNameAmbiguous_WithRouteUrl
DefaultControllerFactory_ErrorCreatingController
DefaultControllerFactory_NoControllerFound
DefaultControllerFactory_TypeDoesNotSubclassControllerBase
DefaultModelBinder_ValueInvalid
DefaultModelBinder_ValueRequired
DefaultViewLocationCache_NegativeTimeSpan
DependencyResolver_DoesNotImplementICommonServiceLocator
ExceptionViewAttribute_NonExceptionType
ExpressionHelper_InvalidIndexerExpression
FilterAttribute_OrderOutOfRange
HtmlHelper_InvalidHttpMethod
HtmlHelper_InvalidHttpVerb
HtmlHelper_MissingSelectData
HtmlHelper_TextAreaParameterOutOfRange
HtmlHelper_ValidationParameterCannotBeEmpty
HtmlHelper_ValidationParameterMustBeLegal
HtmlHelper_ValidationTypeCannotBeEmpty
HtmlHelper_ValidationTypeMustBeLegal
HtmlHelper_ValidationTypeMustBeUnique
HtmlHelper_WrongSelectDataType
JsonRequest_NotAllowed
ModelBinderAttribute_ErrorCreatingModelBinder
ModelBinderAttribute_TypeNotIModelBinder
ModelBinderDictionary_MultipleAttributes
ModelMetadata_PropertyNotSettable
MvcRazorCodeParser_CannotHaveModelAndInheritsKeyword
MvcRazorCodeParser_ModelKeywordMustBeFollowedByTypeName
MvcRazorCodeParser_OnlyOneModelStatementIsAllowed
OutputCacheAttribute_CannotNestChildCache
OutputCacheAttribute_ChildAction_UnsupportedSetting
OutputCacheAttribute_InvalidDuration
OutputCacheAttribute_InvalidVaryByParam
PrivateAssociatedMetadataTypeTypeDescriptor_MetadataTypeContainsUnknownProperties
RedirectAction_CannotRedirectInChildAction
ReflectedActionDescriptor_CannotCallInstanceMethodOnNonControllerType
ReflectedActionDescriptor_CannotCallMethodsWithOutOrRefParameters
ReflectedActionDescriptor_CannotCallOpenGenericMethods
ReflectedActionDescriptor_CannotCallStaticMethod
ReflectedActionDescriptor_ParameterCannotBeNull
ReflectedActionDescriptor_ParameterNotInDictionary
ReflectedActionDescriptor_ParameterValueHasWrongType
ReflectedAsyncActionDescriptor_CannotExecuteSynchronously
ReflectedParameterBindingInfo_MultipleConverterAttributes
RemoteAttribute_NoUrlFound
RemoteAttribute_RemoteValidationFailed
RequireHttpsAttribute_MustUseSsl
SessionStateTempDataProvider_SessionStateDisabled
SingleServiceResolver_CannotRegisterTwoInstances
SynchronizationContextUtil_ExceptionThrown
TemplateHelpers_NoTemplate
TemplateHelpers_TemplateLimitations
Templates_TypeMustImplementIEnumerable
TypeCache_DoNotModify
ValidatableObjectAdapter_IncompatibleType
ValueProviderResult_ConversionThrew
ValueProviderResult_NoConverterExists
ViewDataDictionary_ModelCannotBeNull
ViewDataDictionary_WrongTModelType
ViewMasterPage_RequiresViewPage
ViewPageHttpHandlerWrapper_ExceptionOccurred
ViewStartPage_RequiresMvcRazorView
ViewUserControl_RequiresViewDataProvider
ViewUserControl_RequiresViewPage
WebFormViewEngine_UserControlCannotHaveMaster
WebFormViewEngine_ViewCouldNotBeCreated
WebFormViewEngine_WrongViewBase

答案 2 :(得分:0)

为本地化错误消息指定消息的简单方法如Integer,Double,Float你可以按照以下方式进行。

[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Resources.Validation))]
[Range(0, int.MaxValue, ErrorMessageResourceName = "ValidateAge", ErrorMessageResourceType = typeof(Resources.Validation))]
[DataType(DataType.Text)]
public string Age { get; set; }

因此,不使用Integer,double和Float使用带Range属性的字符串,并使用它指定自定义本地化错误消息。