2015-01-21 17 views
0

我创建的自定义ASP.Net MVC模型验证,如下所示:不引人注意的客户端验证规则中的验证类型名称必须是唯一的。下面的验证类型被视为不止一次:需要

internal class LocalizedRequiredAttribute : RequiredAttribute, IClientValidatable 
{ 
    public List<string> DependentProperties { get; private set; } 
    public List<string> DependentValues { get; private set; } 
    public string Props { get; private set; } 
    public string Vals { get; private set; } 
    public string RequiredFieldValue { get; private set; } 

    public LocalizedRequiredAttribute(string resourceId = "") 
    { 
     if (string.IsNullOrEmpty(resourceId)) 
      ErrorMessage = ResourcesHelper.GetMessageFromResource("RequiredValidationErrorMessage"); 
     else 
      ErrorMessage = ResourcesHelper.GetMessageFromResource(resourceId); 
    } 

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
    { 
     string msg = FormatErrorMessage(metadata.GetDisplayName()); 
     yield return new ModelClientValidationRequiredRule(msg); //Exception 
    } 
} 
internal class LocalizedNumericRegularExpressionAttribute : RegularExpressionAttribute, IClientValidatable 
{ 
    public LocalizedNumericRegularExpressionAttribute(string resourceId = "") : base(@"^\d+$") 
    { 
     if (string.IsNullOrEmpty(resourceId)) 
      ErrorMessage = ResourcesHelper.GetMessageFromResource("NumberRequiredValidationErrorMessage"); 
     else 
      ErrorMessage = ResourcesHelper.GetMessageFromResource(resourceId); 
    } 

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
    { 
     string msg = FormatErrorMessage(metadata.GetDisplayName()); 
     yield return new ModelClientValidationRequiredRule(msg); //Exception 
    } 
} 

以下是我的模型:

public class MyModel 
{ 
    [LocalizedRequired] 
    [LocalizedNumericRegularExpression] 
    public int Emp_No { get; set; } 
} 

每当我浏览到与上述Model一起形成以下异常。

Validation type names in unobtrusive client validation rules must be unique. The following validation type was seen more than once: required 

上面的代码是确定的,如果我删除IClientValidatable,但客户端验证不起作用。

我的代码有什么问题?

回答

2

我找到了解决办法,我们必须在的Application_Start在Global.asax中

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(LocalizedRequiredAttribute), typeof(RequiredAttributeAdapter)); 
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(LocalizedNumericRegularExpressionAttribute), typeof(RegularExpressionAttributeAdapter)); 
+0

你在哪里找到LocalizedRequiredAttribute和LocalizedNumericRegularExpressionAttribute? – 2016-09-15 21:24:12

+0

这些是'RegularExpressionAttribute'和'RequiredAttribute'的自定义。仔细看问题 – 2017-09-12 05:36:14

0

你把ValidationType同样与MVC自动验证的价值添加以下代码。因此,您必须在ModelClientValidationRule或其派生类中更改ValidationType =“name unique”的值。名称应避免MVC自动生成的名称,如“需要”“日期” ... 其他的解决方案是通过对应用程序把这些代码关闭自动验证启动

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = FALSE;

相关问题