I am currently trying to figure out how to localize the error messages generated by MVC. Let me use the default model binder as an example, so I can explain the problem.
Assuming I have a form, where a user enters thier age. The user then enters "ten" in to the form, but instead of getting the expected error of
"Age must be beween 18 and 25."
the message
"The value 'ten' is not valid for Age."
is displayed.
The entity's age property is defined below:
[Range(18, 25, ErrorMessageResourceType = typeof (Errors),
ErrorMessageResourceName = "Age", ErrorMessage = "Range_ErrorMessage")]
public int Age { get; set; }
After some digging, I notice that this error text comes from the System.Web.Mvc.Resources.DefaultModelBinder_ValueInvalid
in the MvcResources.resx
file.
Now, how can create localized versions of this file?
As A solution, for example, should I download MVC source and add MvcResources.en_GB.resx
, MvcResources.fr_FR.resx
, MvcResources.es_ES.resx
and MvcResources.de_DE.resx
, and then compile my own version of MVC.dll
?
But I don't like this idea. Any one else know a better way?
Localization, on the other hand, is the process of customization to make our application behave depending on the current culture and locale. These two things go together. Image is used from: Globalization. Getting Started. Create MVC application.
Model binding is a well-designed bridge between the HTTP request and the C# action methods. It makes it easy for developers to work with data on forms (views), because POST and GET is automatically transferred into a data model you specify. ASP.NET MVC uses default binders to complete this behind the scene.
MVC doesn't use data bindings like old web api. You have to use model bindings in a MVC or MVVM approach.
Custom Model Binder provides a mechanism using which we can map the data from the request to our ASP.NET MVC Model.
See http://forums.asp.net/p/1512140/3608427.aspx, scroll down to Brad Wilson's reply near the bottom of that page (Sat, Jan 09 2010, 3:20 PM). There are static properties on the DefaultModelBinder that you can set to localize the generic error messages.
The reason a generic error message is used instead of your [Range] message is that [Range] provides a validation error message, but this particular case is a binding error. There's absolutely no way the framework can ever hope to convert the string "ten" to an Int32, so it can't even fire the [Range] validator. This is what the "PropertyValueInvalid" key as mentioned in that forum controls.
In MVC3 do the following to change default messages:
DefaultModelBinder.ResourceClassKey = "MyResources";
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