MVC3 localization for default validation errors

时间秒杀一切 提交于 2019-12-12 13:23:21

问题


When I put [Required] attribute on my ViewModel's property MVC3 automatically generate error messages like: The Price field is required.

My site's single language is Russian, so I want to have localized error messages. I can localize field's name with [Display(Name = "blablabla")], but how can I localize the field is required part?

Update: I know, that I can change an error message for concrete field by specifying it [Required(ErrorMessage = "blablabla")], is there a way I can change it in one place for all [Required] attributes, so I could use just [Required] without additional parameters, and it took the localized error message from some ressource/config/etc?


回答1:


I've created an alternative solution where you don't have to use the attributes for the localization. I've created custom model/validation meta data providers.

All you need to do is to download my code and do the following in your global.asax:

var stringProvider = new ResourceStringProvider(Resources.LocalizedStrings.ResourceManager);
ModelMetadataProviders.Current = new LocalizedModelMetadataProvider(stringProvider);
ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(new LocalizedModelValidatorProvider(stringProvider));

(the ResourceStringProvider is my default implementation but it's easy to create an alternative that reads from XML files or a database)

You can read about it here: http://blog.gauffin.org/2011/09/easy-model-and-validation-localization-in-asp-net-mvc3/

I'm going to release a nuget package as soon as I'm finished with my view localization and my alternative HTML helpers.




回答2:


The Required attribute has properties that allow the message to be read from a resource string. See http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.requiredattribute.aspx for the details




回答3:


Granted for this you should already have some Resource Manager which can return localized texts for string keys. My ResourceManager has static accessor for this (and registrations with Unity for DI), so there's no need to pass it. In the global.asax:

ModelMetadataProviders.Current = new LocalizedModelMetadataProvider(); //field name localization
ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(new LocalizedModelValidatorProvider()); //validation message localization

And the implementation is this:

public class LocalizedModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
    protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType,
                                                    Func<object> modelAccessor, Type modelType, string propertyName)
    {

        var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

        if (containerType == null || propertyName == null)
            return metadata;

        if (metadata.DisplayName == null)
            metadata.DisplayName = ResourceManager.Current.GetLocalizedAttribute(containerType, propertyName);

        if (metadata.Watermark == null)
            metadata.Watermark = ResourceManager.Current.GetLocalizedAttribute(containerType, propertyName, "Watermark");

        if (metadata.Description == null)
            metadata.Description = ResourceManager.Current.GetLocalizedAttribute(containerType, propertyName, "Description");

        if (metadata.NullDisplayText == null)
            metadata.NullDisplayText = ResourceManager.Current.GetLocalizedAttribute(containerType, propertyName, "NullDisplayText");

        if (metadata.ShortDisplayName == null)
            metadata.ShortDisplayName = ResourceManager.Current.GetLocalizedAttribute(containerType, propertyName, "ShortDisplayName");

        return metadata;
    }
}

public class LocalizedModelValidatorProvider : DataAnnotationsModelValidatorProvider
{
    protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
    {
        foreach (var attribute in attributes.OfType<ValidationAttribute>())
            attribute.ErrorMessage = ResourceManager.Current.GetValidationMessage(attribute);

        return base.GetValidators(metadata, context, attributes);
    }
}



回答4:


Simply add/change the globalization tag in web.config:

<system.web>
  <globalization uiCulture="your culture"/>


来源:https://stackoverflow.com/questions/7673084/mvc3-localization-for-default-validation-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!