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?
Edit:
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"; } } }
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With