Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customised error messages are not translated in ASP.NET MVC 4

I want to translate the validation message "The field Date must be a date."

I've added the following keys into Application_Start() at Global.asax

ClientDataTypeModelValidatorProvider.ResourceClassKey = "ModelBinders";
DefaultModelBinder.ResourceClassKey = "ModelBinders";

I've created ModelBinders.resx, ModelBinders.nl.resx, ModelBinders.fr.resx in App_GlobalResources.

I've added the following string resources (or translations) in the .resx files:

Name                   Value
====                   =====
FieldMustBeDate        The field {0} must be a date.
FieldMustBeNumeric     The field {0} must be a number.
PropertyValueInvalid   The value '{0}' is not valid for {1}.
PropertyValueRequired  A value is required.

When I submit a string for a date, I will receive the translation for "FieldMustBeDate". When I submit an invalid date (for example "01/01/201a") I receive the untranslated message for "PropertyValueInvalid" that is defined in the default ModelBinders.resx , instead of the translation... How can I show the correct translation for PropertyValueInvalid?

like image 569
LDW Avatar asked Nov 12 '14 15:11

LDW


1 Answers

I'll explain how I specific client messages. First, in the model you set the resource:

    [Required(ErrorMessageResourceType = typeof(Resources.ModelBinders), ErrorMessageResourceName = "Required")]
    [Display(Name = "UserName", ResourceType = typeof(Resources.ModelBinders))]
    public string UserName { get; set; }

Second, in the the controller you overwrite thread culture, I get that from a route, for example in the Initialize method:

    protected override void Initialize(RequestContext requestContext)
    {
        string cultureInfo = requestContext.RouteData.GetRequiredString("cultureInfo");
        System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(cultureInfo);
        System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(cultureInfo);
        base.Initialize(requestContext);
    }

Client messages in English

Client messages in Spanish

It is important that resources are properly formatted: ModelBinders.resx, ModelBinders.es-ES.resx, ModelBinders.en-US.resx ... And nothing else, It works for me well. I hope this approach will help you.

like image 124
Jose M. Avatar answered Nov 15 '22 00:11

Jose M.