简体   繁体   中英

MVC Localization of Default Model Binder

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?

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:

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

Have you tried: IDataErrorInfo property

This article will help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM