2015-01-21 68 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;