MVC 4 忽略 DefaultModelBinder.ResourceClassKey [英] MVC 4 ignores DefaultModelBinder.ResourceClassKey
问题描述
使用 PropertyValueRequired
键将资源文件添加到 App_GlobalResources
并将 DefaultModelBinder.ResourceClassKey
更改为文件名对 MVC 4 没有影响.字符串 The {0} field is required
永远不会改变.我不想在每个必填字段上设置资源类类型和键.我错过了什么吗?
Adding a resource file to App_GlobalResources
with a PropertyValueRequired
key and changing DefaultModelBinder.ResourceClassKey
to the file name has no effect on MVC 4. The string The {0} field is required
is never changed.
I don't want to set the resource class type and key on every required field.
Am I missing something?
我对 Darin Dimitrov 的代码做了一些小的修改,以保持必需的自定义工作:
I've made a small modification on Darin Dimitrov's code to keep Required customizations working:
public class MyRequiredAttributeAdapter : RequiredAttributeAdapter
{
public MyRequiredAttributeAdapter(
ModelMetadata metadata,
ControllerContext context,
RequiredAttribute attribute
)
: base(metadata, context, attribute)
{
if (attribute.ErrorMessageResourceType == null)
{
attribute.ErrorMessageResourceType = typeof(Messages);
}
if (attribute.ErrorMessageResourceName == null)
{
attribute.ErrorMessageResourceName = "PropertyValueRequired";
}
}
}
推荐答案
这不是特定于 ASP.NET MVC 4.它在 ASP.NET MVC 3 中是相同的.您不能使用 DefaultModelBinder 设置所需的消息.ResourceClassKey
,只有PropertyValueInvalid
.
This is not specific to ASP.NET MVC 4. It was the same in ASP.NET MVC 3. You cannot set the required message using DefaultModelBinder.ResourceClassKey
, only the PropertyValueInvalid
.
实现您所需要的一种方法是定义自定义RequiredAttributeAdapter
:
One way to achieve what you are looking for is to define a custom RequiredAttributeAdapter
:
public class MyRequiredAttributeAdapter : RequiredAttributeAdapter
{
public MyRequiredAttributeAdapter(
ModelMetadata metadata,
ControllerContext context,
RequiredAttribute attribute
) : base(metadata, context, attribute)
{
attribute.ErrorMessageResourceType = typeof(Messages);
attribute.ErrorMessageResourceName = "PropertyValueRequired";
}
}
您将在 Application_Start
中注册:
DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof(RequiredAttribute),
typeof(MyRequiredAttributeAdapter)
);
现在当一个不可为空的字段没有被赋值时,错误信息将来自 Messages.PropertyValueRequired
其中 Messages.resx
必须在 中定义App_GlobalResources
.
Now when a non-nullable field is not assigned a value, the error message will come from Messages.PropertyValueRequired
where Messages.resx
must be defined inside App_GlobalResources
.
这篇关于MVC 4 忽略 DefaultModelBinder.ResourceClassKey的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!