基于以下链接:Multi Language - Data Annotations 进行一系列的类来翻译数据注释的文本。 在服务器端一切正常,但客户端验证无效。
如果我使用:[System.ComponentModel.DataAnnotations.Required]
public string Name { get; set; }
客户端上的验证正常运行,但是如果我使用:
[Infrastructure.Required]//My custom class
public string Name { get; set; }
它仅在服务器端起作用。
这是我当前正在使用的课程:
namespace project.Infrastructure
{
public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute
{
private string _displayName;
public RequiredAttribute()
{
ErrorMessageResourceName = "Validation_Required";
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
_displayName = validationContext.DisplayName;
return base.IsValid(value, validationContext);
}
public override string FormatErrorMessage(string name)
{
var msg = WebsiteTranslations.GetTranslationErrorMessage(Settings.LanguageId, "Required", WebsiteTranslations.GetTranslation(name, 1, Settings.LanguageId));
return string.Format(msg, _displayName);
}
public System.Collections.IEnumerable GetClientValidationRules(System.Web.Mvc.ModelMetadata metadata, ControllerContext context)
{
return new[] { new ModelClientValidationRequiredRule((ErrorMessage)) };
}
}
}
答案 0 :(得分:0)
我从这篇文章中得到了答案:validation-type-names-in-unobtrusive GetClientValidationRules方法如下:
public IEnumerable GetClientValidationRules(System.Web.Mvc.ModelMetadata metadata, ControllerContext context)
{
var clientValidationRule = new ModelClientValidationRule()
{
ErrorMessage = FormatErrorMessage(ErrorMessage),
ValidationType = "required"
};
yield return new[] { clientValidationRule };
}
在Global.asax中的Application_Start中:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredAttribute), typeof(RequiredAttributeAdapter));
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(StringLengthAttribute), typeof(StringLengthAttributeAdapter));