2011-03-23 109 views
0

我使用asp.net MVC 3,在我的模塊中有兩種付款方式1.電匯和2. PayPal。現在取決於這種類型1和2,屬性將被保存爲必需或其他數據註釋!這個怎麼做 ? 爲如:幫助mvc條件模型驗證

有一個單選按鈕,付款方式,

如果鍵入1-即電匯被選中,那麼這些字段應驗證 - 姓,名,電子郵件,收款人姓名,銀行名稱,銀行號,ifsc代碼等 如果它是類型2即貝寶然後這些字段是必需的 - 貝寶電子郵件。

這可以通過手動驗證來完成,但有什麼方法可以通過DataAnnotations以正確的方式進行?

回答

1

你可以寫一個自定義的驗證屬性,並用它裝點你的模型:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] 
public class CustomValidationAttribute : ValidationAttribute 
{ 
    public override bool IsValid(object value) 
    { 
     var model = value as MyViewModel; 
     if (model == null) 
     { 
      return false; 
     } 
     if (model.WireTransfer == 1) 
     { 
      return !string.IsNullOrEmpty(model.FirstName) && 
        !string.IsNullOrEmpty(model.LastName); 
     } 
     else if (model.WireTransfer == 2) 
     { 
      return !string.IsNullOrEmpty(model.PaypalEmail); 
     } 
     return false; 
    } 
} 

,然後在你的主要型號:

[CustomValidation] 
public class MyViewModel 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    ... 
} 
+0

thnx !!但問題是,在這種情況下,客戶端驗證不會工作? – bhuvin 2011-03-23 07:25:09

+0

@bhuvin,不,它不會工作,但你可以通過實現IClientValidatable來實現它:http://devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp .net-mvc-3-part-2 – 2011-03-23 07:28:32

+0

@darin已經嘗試過與其他東西,但它仍然沒有工作 – bhuvin 2011-03-23 07:29:47

0

我已經使用的方法從Simon Ince's blog post,而且運作良好。基本上他創建了一個RequiredIf數據屬性,您可以在其中指定其他屬性和必須爲true的值以使當前字段成爲必需。

4

西蒙因斯的博客文章似乎已經過時。

無需使用DataAnnotationsModelValidator或執行DataAnnotationsModelValidator註冊。

您可以使用下面的代碼:

[AttributeUsage(AttributeTargets.Property, AllowMultiple=false)] 
public class RequiredIfAttribute : ValidationAttribute, IClientValidatable { 
    private const string _defaultErrorMessage = "'{0}' is required when {1} equals {2}."; 

    public string DependentProperty { get; set; } 
    public object TargetValue { get; set; } 

    public RequiredIfAttribute(string dependentProperty, object targetValue):base(_defaultErrorMessage) { 
     this.DependentProperty = dependentProperty; 
     this.TargetValue = targetValue; 
    } 
    public override string FormatErrorMessage(string name) { 
     return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, DependentProperty, TargetValue); 
    } 
    protected override ValidationResult IsValid(object value, ValidationContext context) { 
     if (context.ObjectInstance != null) { 
      Type type = context.ObjectInstance.GetType(); 
      PropertyInfo info = type.GetProperty(DependentProperty); 
      object dependentValue; 
      if (info != null) { 
       dependentValue = info.GetValue(context.ObjectInstance, null); 
       if (object.Equals(dependentValue, TargetValue)) { 
        if (string.IsNullOrWhiteSpace(Convert.ToString(value))) { 
         return new ValidationResult(ErrorMessage); 
        } 
       } 
      } 
     } 
     return ValidationResult.Success; 
    } 
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { 
     ModelClientValidationRule rule = new ModelClientValidationRule(); 
     rule.ErrorMessage = this.FormatErrorMessage(metadata.PropertyName); 
     rule.ValidationType = "requiredif"; 
     rule.ValidationParameters.Add("depedentproperty", DependentProperty); 
     rule.ValidationParameters.Add("targetvalue", TargetValue); 
     yield return rule; 
    } 
} 

和JavaScript的一面:如果你正在使用jQuery:

$.validator.unobtrusive.adapters.add('requiredif', ['depedentproperty', 'targetvalue'], function (options) { 
    options.rules["required"] = function (element) { 
     return $('#' + options.params.depedentproperty).val() == options.params.targetvalue 
    }; 
    if (options.message) { 
     options.messages["required"] = options.message; 
    } 
    $('#' + options.params.depedentproperty).blur(function() { 
     $('#' + options.element.name).valid(); 
    }); 
});