Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 4 ignores DefaultModelBinder.ResourceClassKey

Tags:

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";         }     } } 
like image 556
Eduardo Avatar asked Sep 22 '12 15:09

Eduardo


1 Answers

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.

like image 181
Darin Dimitrov Avatar answered Oct 12 '22 01:10

Darin Dimitrov