如何本地化数据类型消息

时间:2013-03-07 11:30:32

标签: c# asp.net-mvc-4

如何在MVC4中本地化数据类型消息“字段日期必须是日期。”

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

我用:

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";
        }

    }

LocalizedDataTypeAttributeAdapter也在Global.asax中注册

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(DataTypeAttribute), typeof(LocalizedDataTypeAttributeAdapter));

1 个答案:

答案 0 :(得分:1)

您需要重写ClientDataTypeModelValidatorProvider

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

并更改

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;
        }

然后在Global.asax的DefaultModelBinder期间将其设置为Application_Start

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;
}