使用App_GlobalResources键向PropertyValueRequired添加资源文件并将DefaultModelBinder.ResourceClassKey更改为文件名对MVC 4没有影响。字符串The {0} field is required从未更改过。我不想在每个必需的字段上设置资源类类型和键。我是不是遗漏了什么?
编辑:
我对达林·季米特洛夫的代码做了一个小小的修改,以保证所需的自定义工作:
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";
}
}
}发布于 2012-09-22 17:17:32
这并不是特定于ASP.NET MVC 4,在ASP.NET MVC 3中也是如此,您不能使用DefaultModelBinder.ResourceClassKey来设置所需的消息,只能使用PropertyValueInvalid。
实现您正在寻找的目标的一种方法是定义自定义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,其中必须在App_GlobalResources中定义Messages.resx。
https://stackoverflow.com/questions/12545176
复制相似问题