MVC 多语言记录1 设置默认的ResourceType

时间:2021-07-30 09:01:54

http://*.com/questions/3260748/default-resource-for-data-annotations-in-asp-net-mvc

Add this class somewhere in your project:

 public class ExternalResourceDataAnnotationsValidator : DataAnnotationsModelValidator<ValidationAttribute>
{
/// <summary>
/// The type of the resource which holds the error messqages
/// </summary>
public static Type ResourceType { get; set; } /// <summary>
/// Function to get the ErrorMessageResourceName from the Attribute
/// </summary>
public static Func<ValidationAttribute, string> ResourceNameFunc
{
get { return _resourceNameFunc; }
set { _resourceNameFunc = value; }
}
private static Func<ValidationAttribute, string> _resourceNameFunc = attr => attr.GetType().Name; public ExternalResourceDataAnnotationsValidator(ModelMetadata metadata, ControllerContext context, ValidationAttribute attribute)
: base(metadata, context, attribute)
{
if (Attribute.ErrorMessageResourceType == null)
{
this.Attribute.ErrorMessageResourceType = ResourceType;
} if (Attribute.ErrorMessageResourceName == null)
{
this.Attribute.ErrorMessageResourceName = ResourceNameFunc(this.Attribute);
}
}
}

and in your global.asax, add the following:

// Add once
ExternalResourceDataAnnotationsValidator.ResourceType = typeof(CustomDataAnnotationsResources); // Add one line for every attribute you want their ErrorMessageResourceType replaced.
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RangeAttribute), typeof(ExternalResourceDataAnnotationsValidator));

It will look for a property with the same name as the validator type for the error message. You can change that via the ResourceNameFunc property.

EDIT: AFAIK this works from MVC2 onwards, as DataAnnotationsModelValidatorProvider was introduced in MVC2.


To achieve this, I created a new class that inherits from RequiredAttribute, and the error message is embedded inside this new class:

The error message is taken from the ValidationResource.resx file, where I list the error message as follows:

public class RequiredWithMessageAttribute : RequiredAttribute
{
public RequiredWithMessageAttribute()
{
ErrorMessageResourceType = typeof(ValidationResource);
ErrorMessageResourceName = "RequiredErrorMessage";
}
}

RequiredErrorMessage --> "{0} is required."

where {0} = display name.

I then annotate my models like this, so I never have to repeat my error message declarations:

[RequiredWithMessage]
public string Name { get; set; }

Once you do this, an error message ("Name is required.") will appear whenever validation fails.

This works properly with ASP.NET MVC's server-side validation and client-side validation.