Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to localize datatype messages

How to localize datatype messages in MVC4 "The field Date must be a date."

<input data-val="true" data-val-date="The field Date be a date." id="Date" name="Date"  value="" >

I using:

public class LocalizedDataTypeAttributeAdapter : DataAnnotationsModelValidator<DataTypeAttribute>

        {
            public LocalizedDataTypeAttributeAdapter(ModelMetadata metadata, ControllerContext context, DataTypeAttribute attribute) : base(metadata, con

text, attribute)
        {
            attribute.ErrorMessageResourceType = typeof(Localization.Global);
            attribute.ErrorMessageResourceName = "PropertyDataFormat";
        }

    }

Also LocalizedDataTypeAttributeAdapter register in Global.asax

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(DataTypeAttribute), typeof(LocalizedDataTypeAttributeAdapter));
like image 576
user2143934 Avatar asked Mar 07 '13 11:03

user2143934


1 Answers

You need to rewrite ClientDataTypeModelValidatorProvider

Take it https://github.com/mono/aspnetwebstack/blob/master/src/System.Web.Mvc/ClientDataTypeModelValidatorProvider.cs

and change

private static string GetUserResourceString(ControllerContext controllerContext, string resourceName)
        {
            string result = null;

            if (!String.IsNullOrEmpty(ResourceClassKey) && (controllerContext != null) && (controllerContext.HttpContext != null))
            {
                //result = controllerContext.HttpContext.GetGlobalResourceObject(ResourceClassKey, resourceName, CultureInfo.CurrentUICulture) as string;
                result = GlobalRes.ResourceManager.GetString(resourceName);
            }

            return result;
        }

Then set it as the DefaultModelBinder during the Application_Start in Global.asax:

protected void Application_Start()
{

   var existingProvider = ModelValidatorProviders.Providers.Single(x => x is ClientDataTypeModelValidatorProvider);
   ModelValidatorProviders.Providers.Remove(existingProvider);
   ModelValidatorProviders.Providers.Add(new myClientDataTypeModelValidatorProvider()); //!!
   myClientDataTypeModelValidatorProvider.ResourceClassKey = typeof(GlobalRes).Name;
   DefaultModelBinder.ResourceClassKey = typeof(GlobalRes).Name;
}
like image 97
RouR Avatar answered Sep 23 '22 02:09

RouR