using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; using System.Globalization; using Bowin.Common.JSON; namespace EMIS.ViewModel { public class TotalLengthAttribute : ValidationAttribute, IClientValidatable { public int Length { get; set; } public IList RelateControls { get; set; } /// /// /// /// /// public TotalLengthAttribute(int length, params string[] relateControls) { this.Length = length; if (relateControls == null) { RelateControls = new List(); } else { RelateControls = relateControls.ToList(); } } /// /// /// /// /// /// protected override ValidationResult IsValid(object value, ValidationContext validationContext) { string totalString = ""; List errorMessage = new List(); foreach (var relateControl in RelateControls) { var property = validationContext.ObjectType.GetProperty(relateControl); if (property == null) { errorMessage.Add(string.Format(CultureInfo.CurrentCulture, "{0} 不存在", relateControl)); continue; } //获取属性的值 var otherValue = property.GetValue(validationContext.ObjectInstance, null); totalString += Convert.ToString(otherValue); } if (errorMessage.Count > 0) { return new ValidationResult(string.Join(",", errorMessage)); } if (totalString.Length != this.Length) { return new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); } return null; } /// /// /// /// /// /// public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule { ValidationType = "totallength", ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()) }; rule.ValidationParameters["length"] = Length; rule.ValidationParameters["other"] = RelateControls.ToJson(); yield return rule; } } }