如何进行 Web 表单模型验证?

发布于 2024-10-31 19:33:07 字数 839 浏览 1 评论 0原文

我们有一个具有三层的应用程序:UI、业务和数据。数据层包含实体框架 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 Web 表单中利用模型验证的最佳方法是什么?

我确实找到了一篇文章,解释了如何为它构建一个服务器控件,但我似乎无法让它工作。它编译甚至识别该控件,但我永远无法让它启动。

有什么想法吗?

谢谢大家。

We have an application with three layers: UI, Business, and Data. The data layer houses Entity Framework v4 and auto-generates our entity objects. I have created a buddy class for the entity 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;
    }
}

I want this validation to bubble up to the UI, including custom validation messages assigned to them. In MVC this is a piece of cake but in web forms I have no clue where to begin. What is the best way to utilize model validation in asp.net web forms?

I did find an article that explains how to build a server control for it, but I can't seem to get it working. It compiles and even recognizes the control but I can never get it to fire.

Any ideas?

Thanks everyone.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ぶ宁プ宁ぶ 2024-11-07 19:33:07

我解决了。看起来我找到的服务器控件未设计为通过 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
    }

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

I solved it. It would appear that the server control I found was not designed to read fields in a buddy class via the MetadataType attribute. I modified the code to look for its validation attributes in the buddy class rather than the entity class itself.

Here is the modified version of the linked server control:

    [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
    }

This code only looks in the buddy class. If you want it to check an actual class and then its buddy class, you'll have to modify it accordingly. I did not bother doing that because usually if you are using a buddy class for validation attributes it's because you are not able to use the attributes in the main entity class (e.g. Entity Framework).

别把无礼当个性 2024-11-07 19:33:07

对于 Web 表单中的模型验证,我使用 DAValidation 库。它支持客户端验证(包括非侵入式验证),以及基于与 MVC 相同原理的可扩展性。它已获得 MS-PL 许可,可通过 Nuget 获取。

这是有点过时的文章描述思想控制是如何建立的。

For model validation in web forms I'm using DAValidation library. It supports validation on client side (including unobtrusive validation), extensibility based on same principles as in MVC. It is MS-PL licensed and available via Nuget.

And here is bit out of date article describing with what thoughts control was build.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文