Default MVC Localization

I'm currently trying to figure out how to localize the error messages generated by MVC. Let me use standard model binding as an example, so I can explain the problem.

Assuming I have a form in which a user enters age. Then the user enters the "top ten" in the form, but instead of receiving the expected error

"Age must be between 18 and 25 years old."

message

"The value ten is not valid for Age."

.

The age property of an object 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 System.Web.Mvc.Resources.DefaultModelBinder_ValueInvalid in the MvcResources.resx file.

Now, how to create localized versions of this file?

As a solution, for example, you need to download the 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 do not like this idea. Does anyone know a better way?

+6
asp.net-mvc globalization resx
source share
3 answers

See http://forums.asp.net/p/1512140/3608427.aspx , scroll down to Brad Wilson's answer at the bottom of this page (Sat, Jan. 09, 2010, 3:20 p.m.). DefaultModelBinder has static properties that can be configured to localize common error messages.

The reason you use a generic error message instead of your [Range] message is because [Range] provides a validation error message, but this particular case is a binding error. There is absolutely no way that the infrastructure can ever hope to convert the string ten to Int32, so it cannot even run the [Range] validator. This is what controls the PropertyValueInvalid key mentioned in this forum.

+5
source share

In MVC3, to change the default messages, follow these steps:

  • add the App_GlobalResources folder to your ASP.NET site
  • add a new resource file, name it f.ex. MyResources.resx
  • add these keys
    • PropertyValueRequired : value required.
    • PropertyValueInvalid : the value {{0} "is not valid for {1}.
  • in Application_Start from global.asax.cs add the line DefaultModelBinder.ResourceClassKey DefaultModelBinder.ResourceClassKey = "MyResources";
+3
source share
0
source share

All Articles