Localization in ASP.NET MVC 4 using App_GlobalResources

前端 未结 2 1624
隐瞒了意图╮
隐瞒了意图╮ 2021-02-09 05:11

I am trying to accomplish two things:

  1. Localize the “built-in” error messages for “FieldMustBeDate” and \"FieldMustBeNumeric\".
  2. Localize some of the other
2条回答
  •  [愿得一人]
    2021-02-09 06:12

    I have made some minor additions to the original post, which didn't translate all messages in my case. (String length and invalid property values)

    Follow the above steps, to create the *.resx files, set their properties, and then set the locale in web.config, as described by Andreas.

    Then create a couple of adapters:

    // As described in original post:
    public class LocalizedRequiredAttributeAdapter : RequiredAttributeAdapter
    {
        public LocalizedRequiredAttributeAdapter(
            ModelMetadata metadata,
            ControllerContext context,
            RequiredAttribute attribute
        )
            : base(metadata, context, attribute)
        {
            if (attribute.ErrorMessageResourceType == null)
                attribute.ErrorMessageResourceType = typeof(Resources.Resources);
            if (attribute.ErrorMessageResourceName == null)
                attribute.ErrorMessageResourceName = "PropertyValueRequired";
        }
    }
    
    // Addition to original post:
    public class LocalizedStringLengthAttributeAdapter : StringLengthAttributeAdapter
    {
        public LocalizedStringLengthAttributeAdapter(
            ModelMetadata metadata,
            ControllerContext context,
            StringLengthAttribute attribute
        )
            : base(metadata, context, attribute)
        {
            if (attribute.ErrorMessageResourceType == null)
                attribute.ErrorMessageResourceType = typeof(Resources.Resources);
            if (attribute.ErrorMessageResourceName == null)
                attribute.ErrorMessageResourceName = "StringLengthAttribute_ValidationError";
        }
    }
    

    And in Global.asax.cx:

    // Addition to original post: (Used for "PropertyValueInvalid")
    DefaultModelBinder.ResourceClassKey = "Resources";
    
    // As described in original post:
    ClientDataTypeModelValidatorProvider.ResourceClassKey = "Resources";
    DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredAttribute), typeof(LocalizedRequiredAttributeAdapter));
    DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(StringLengthAttribute), typeof(LocalizedStringLengthAttributeAdapter));
    

提交回复
热议问题