如何使用来自不同程序集的资源来覆盖MVC5应用程序中的默认属性错误消息?
我的网站是命名空间:Company.Web
我的资源程序集是命名空间:Company.Web.Resources
我可以使用以下方法单独本地化属性错误消息:
[Required(ErrorMessageResourceName = "PropertyValueRequired", ErrorMessageResourceType = typeof(Company.Web.Resources.Messages))]
但是,由于我们的错误消息始终是“必需”,因此我只想放置[Required]
属性而无需指定资源名称。我还想覆盖MVC输出的默认数据类型消息,这是通过属性无法完成的。
字段{0}必须是日期。
我想成为
失效日期
我已经看到了一些示例,您可以将资源文件放在App_GlobalResources(使用密钥PropertyValueRequired
,FieldMustBeDate
,FieldMustBeNumeric
)和设置ClientDataTypeModelValidatorProvider.ResourceClassKey
,但我已经有一个我想要使用的外部资源程序集。
我已经尝试在我的Global.asax中使用以下内容而没有运气:
ClientDataTypeModelValidatorProvider.ResourceClassKey = "Company.Web.Resources.Messages"
我怎么能做到这一点?有任何想法吗?
更新(部分决议)
我可以通过创建新的验证适配器并使用它们来代替默认值来解决基于属性的问题:
public class MyRequiredAttributeAdapter : RequiredAttributeAdapter
{
public MyRequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
: base(metadata, context, attribute)
{
if (attribute.ErrorMessage.IsNullOrWhitespace()
&& attribute.ErrorMessageResourceName.IsNullOrWhitespace()
&& attribute.ErrorMessageResourceType == null)
{
attribute.ErrorMessageResourceType = typeof (Resources.Validation.Messages);
attribute.ErrorMessageResourceName = "PropertyValueRequired";
}
}
}
Global.asax中
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredAttribute), typeof(MyRequiredAttributeAdapter));
但是,这仍然让我不知道如何覆盖非null属性(如DateTime和int)的默认数据类型消息。此外,我相信有一些我无法覆盖,因为它们是内部的(DataTypeAttributeAdapter,CompareAttributeAdapter)。
这可能很晚,但是这里的解决方案应该主要基于部分解决方案背后的逻辑。
RequiredAttribute
public class MyRequiredAttribute : RequiredAttribute
{
//Your custom code
}
MyRequiredAttributeAdapter
代码,如图所示。请注意,您现在需要继承通用的DataAnnotationsModelValidator
类,它允许您传入自定义MyRequiredAttribute
public class MyRequiredAttributeAdapter : DataAnnotationsModelValidator<MyRequiredAttribute>
{
public MyRequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, MyRequiredAttribute attribute)
: base(metadata, context, attribute)
{
if (string.IsNullOrWhiteSpace(attribute.ErrorMessage)
&& string.IsNullOrWhiteSpace(attribute.ErrorMessageResourceName)
&& attribute.ErrorMessageResourceType == null)
{
attribute.ErrorMessageResourceType = typeof(Resources.Validation.Messages);
attribute.ErrorMessageResourceName = "PropertyValueRequired";
}
}
}
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyRequiredAttribute), typeof(MyRequiredAttributeAdapter));
要覆盖非null属性(如DateTime和int)的默认数据类型消息,
基于MVC MyClientDataTypeModelValidatorProvider
实现自己的ClientDataTypeModelValidatorProvider
。
将该实例添加到ModelValidatorProviders.Providers
,并删除默认实例。
所以,把它放到Global.asax中:
var clientDataTypeModelValidatorProviderIndex = ModelValidatorProviders.Providers.FindIndex(modelValidatorProvider => modelValidatorProvider is ClientDataTypeModelValidatorProvider);
ModelValidatorProviders.Providers.RemoveAt(clientDataTypeModelValidatorProviderIndex);
ModelValidatorProviders.Providers.Add(new MyClientDataTypeModelValidatorProvider());
用MVC 5测试