【问题标题】:How do you do web forms model validation?您如何进行 Web 表单模型验证?
【发布时间】:2011-04-08 20:58:35
【问题描述】:

我们有一个包含三层的应用程序: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;
    }
}

我希望此验证能够冒泡到 UI,包括分配给它们的自定义验证消息。在 MVC 中,这是小菜一碟,但在 Web 表单中,我不知道从哪里开始。在 asp.net 网络表单中使用模型验证的最佳方式是什么?

我确实找到了an article,它解释了如何为其构建服务器控件,但我似乎无法让它工作。它可以编译甚至识别控件,但我永远无法触发它。

有什么想法吗?

谢谢大家。

【问题讨论】:

  • 很遗憾,我无法回答有关 WebForms 中 DataAnnotation 验证的具体问题。但我建议您考虑将 T4 模板移动到单独的模型/业务实体程序集,以防止您的 UI 需要直接依赖于数据层。

标签: c# asp.net validation entity-framework-4 model


【解决方案1】:

我解决了。看来server control I found 并非旨在通过 MetadataType 属性读取伙伴类中的字段。我修改了代码以在伙伴类而不是实体类本身中查找其验证属性。

这里是链接服务器控件的修改版本:

    [DefaultProperty("Text")]
    [ToolboxData("<{0}:DataAnnotationValidator runat=server></{0}:DataAnnotationValidator>")]
    public class DataAnnotationValidator : BaseValidator
    {
        #region Properties

        /// <summary>
        /// The type of the source to check
        /// </summary>
        public string SourceTypeName { get; set; }

        /// <summary>
        /// The property that is annotated
        /// </summary>
        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<ValidationAttribute>())
            {
                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<MetadataTypeAttribute> mt = validatedType.GetCustomAttributes(typeof(MetadataTypeAttribute), false).OfType<MetadataTypeAttribute>();
            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
    }

此代码在伙伴类中查找。如果你想让它检查一个实际的班级,然后检查它的伙伴班级,你必须相应地修改它。我没有这样做,因为通常如果您使用伙伴类来验证属性,那是因为您无法使用主实体类(例如实体框架)中的属性。

【讨论】:

    【解决方案2】:

    对于网络表单中的模型验证,我使用DAValidation 库。它支持客户端验证(包括不显眼的验证),基于与 MVC 相同原则的可扩展性。它已获得 MS-PL 许可,可通过 Nuget 获得。

    这里有点过时了 article 描述的思想控制是什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 2017-04-11
      • 1970-01-01
      • 2013-10-22
      相关资源
      最近更新 更多