2011-03-23 108 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(); 
    }); 
});