using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web.Mvc; namespace EnVisage.Models.ValidationAttributes { public class ValidationAttributeBase : ValidationAttribute { protected List GetMetadata(ModelMetadata metadata, ControllerContext context) { if (metadata == null || context == null) return new List(); var _metadata = new List(); if (metadata.Container != null) { var containerProperties = ModelMetadataProviders.Current.GetMetadataForProperties(metadata.Container, metadata.ContainerType).ToList(); if (containerProperties != null && containerProperties.Count > 0) _metadata.AddRange(containerProperties); } if (metadata.Container != null && context.Controller.ViewData.Model != null && metadata.ContainerType != context.Controller.ViewData.Model.GetType()) { var modelProperties = ModelMetadataProviders.Current.GetMetadataForProperties(context.Controller.ViewData.Model, context.Controller.ViewData.Model.GetType()).ToList(); if (modelProperties != null) { var missingProperties = modelProperties.FindAll(x => _metadata.All(s => s.PropertyName != x.PropertyName)); if (missingProperties != null && missingProperties.Count > 0) _metadata.AddRange(modelProperties); } } return _metadata; } protected object GetPropertyValue(string propertyName, ModelMetadata metadata, ControllerContext context) { var properties = GetMetadata(metadata, context); if (properties == null || properties.Count <= 0) return null; var property = properties.FirstOrDefault(x => x.PropertyName == propertyName); if (property == null) return null; return property.Model; } } }