2016-02-09 54 views
-1

如何進行條件數據註釋? 如何在需要屬性值取決於其他屬性值時準備數據註釋驗證?必填如果數據數據註釋需要檢查驗證

我已經編寫如下:

[RequiredIf("property_name==\"property_Value\"", ErrorMessageResourceType = typeof(Resources.resfilename), ErrorMessageResourceName = "ErrMessage")] 
     public int? propertyname { get; set; } 

如何生成所需的,如果上課嗎?

回答

0

創建如下類:

using System; 
using System.Collections.Generic; 
using System.Linq.Expressions; 
using System.ComponentModel.DataAnnotations; 
using System.Web.Mvc; 

namespace BusinessModels 
{ 
    public class RequiredIfAttribute : ValidationAttribute, IClientValidatable 
    { 
     private readonly string _condition; 

     public RequiredIfAttribute(string condition) 
     { 
      _condition = condition; 
     } 

     protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
     { 
      Delegate conditionFunction = CreateExpressionDelegate(validationContext.ObjectType, _condition); 

      bool conditionMet = (bool) conditionFunction.DynamicInvoke(validationContext.ObjectInstance); 

      if (conditionMet) 
      { 
       if (value == null) 
       { 
        return new ValidationResult(FormatErrorMessage(null)); 
       } 
      } 
      return null; 
     } 

     private Delegate CreateExpressionDelegate(Type objectType, string expression) 
     { 
      // TODO - add caching 
      var lambdaExpression = CreateExpression(objectType, expression); 
      Delegate func = lambdaExpression.Compile(); 
      return func; 
     } 

     private LambdaExpression CreateExpression(Type objectType, string expression) 
     { 
      // TODO - add caching 
      LambdaExpression lambdaExpression = 
       System.Linq.Dynamic.DynamicExpression.ParseLambda(
        objectType, typeof(bool), expression); 
      return lambdaExpression; 
     } 

     public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
     { 
      string errorMessage = FormatErrorMessage(metadata.GetDisplayName()); 

      Expression expression = CreateExpression(metadata.ContainerType, _condition); 
      var visitor = new JavascriptExpressionVisitor(); 
      string javascriptExpression = visitor.Translate(expression); 

      var clientRule = new ModelClientValidationRule 
      { 
       ErrorMessage = errorMessage, 
       ValidationType = "requiredif", 
       ValidationParameters = 
             { 
              { "expression", javascriptExpression } 
             } 
      }; 

      return new[] { clientRule }; 
     } 

    } 
} 

和屬性調用像如下:

[RequiredIf("property_name==\"prop_value\"", ErrorMessageResourceType = typeof(Resources.resfilename), ErrorMessageResourceName = "ErrMessage")] 
     public int? propertyname { get; set; }