MVC 4 ignores DefaultModelBinder.ResourceClassKey

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.

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";
    }
}

that you will register in Application_Start:

DataAnnotationsModelValidatorProvider.RegisterAdapter(
    typeof(RequiredAttribute),
    typeof(MyRequiredAttributeAdapter)
);

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.

Leave a Comment