views:

307

answers:

2

Hi,

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?

A: 

Have you tried: IDataErrorInfo property

This article will help

Asad Butt
For Validation, I use Fluent Validation. The problem here is not with validation, i think? The problem is that the MVC , or in this case, the default model binder is not localizing the error messages when it adds its own error message to the ModelState.Error dictionary. I want to use exactly the same behaviour as the default model binder provides, but I want to localize those error messages to other languages
Dai Bok
+1  A: 

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.

Levi
Thanks, thats exactly what I am looking for.
Dai Bok