你如何进行Web表单模型validation?
我们有一个包含三个层的应用程序:UI,业务和数据。 数据层包含Entity Framework v4并自动生成我们的实体对象。 我为实体VendorInfo
创建了一个伙伴类:
namespace Company.DataAccess { [MetadataType(typeof(VendorInfoMetadata))] public partial class VendorInfo { } public class VendorInfoMetadata { [Required] public string Title; [Required] public string Link; [Required] public string LinkText; [Required] public string Description; } }
我希望此validation可以冒泡到UI,包括分配给它们的自定义validation消息。 在MVC中,这是一块蛋糕,但在网络forms中,我不知道从哪里开始。 在asp.net Web表单中使用模型validation的最佳方法是什么?
我找到了一篇文章 ,解释了如何为它构建一个服务器控件,但我似乎无法让它工作。 它编译甚至识别控制,但我永远无法解决它。
有任何想法吗?
感谢大家。
我解决了 看起来我发现的服务器控件并不是设计用于通过MetadataType属性读取伙伴类中的字段。 我修改了代码以在buddy类中查找其validation属性,而不是实体类本身。
以下是链接服务器控件的修改版本:
[DefaultProperty("Text")] [ToolboxData("<{0}:DataAnnotationValidator runat=server>{0}:DataAnnotationValidator>")] public class DataAnnotationValidator : BaseValidator { #region Properties /// /// The type of the source to check /// public string SourceTypeName { get; set; } /// /// The property that is annotated /// public string PropertyName { get; set; } #endregion #region Methods protected override bool EvaluateIsValid() { // get the type that we are going to validate Type source = GetValidatedType(); // get the property to validate FieldInfo property = GetValidatedProperty(source); // get the control validation value string value = GetControlValidationValue(ControlToValidate); foreach (var attribute in property.GetCustomAttributes( typeof(ValidationAttribute), true) .OfType()) { if (!attribute.IsValid(value)) { ErrorMessage = attribute.ErrorMessage; return false; } } return true; } private Type GetValidatedType() { if (string.IsNullOrEmpty(SourceTypeName)) { throw new InvalidOperationException( "Null SourceTypeName can't be validated"); } Type validatedType = Type.GetType(SourceTypeName); if (validatedType == null) { throw new InvalidOperationException( string.Format("{0}:{1}", "Invalid SourceTypeName", SourceTypeName)); } IEnumerable mt = validatedType.GetCustomAttributes(typeof(MetadataTypeAttribute), false).OfType (); if (mt.Count() > 0) { validatedType = mt.First().MetadataClassType; } return validatedType; } private FieldInfo GetValidatedProperty(Type source) { FieldInfo field = source.GetField(PropertyName); if (field == null) { throw new InvalidOperationException( string.Format("{0}:{1}", "Validated Property Does Not Exists", PropertyName)); } return field; } #endregion }
此代码仅查看好友类。 如果你想要它检查一个实际的类,然后检查它的伙伴类,你将不得不相应地修改它。 我没有打扰这样做,因为通常如果您使用伙伴类来validation属性,那是因为您无法使用主实体类中的属性(例如entity framework)。
对于Web表单中的模型validation,我使用的是DAValidation库。 它支持客户端validation(包括不显眼的validation),基于与MVC相同的原则的可扩展性。 它是MS-PL许可的,可通过Nuget获得 。
这里有一些过时的文章描述了控制构建的想法。