本文演示Enterprise Library – Validation Application Block 验证管理模块的使用,检查验证操作的返回结果集,从验证失败中获取更多详细的信息。本文由http://blog.entlib.com 开源ASP.NET博客平台小组根据EntLib HOL手册编译提供,欢迎交流。
 
练习二:遍历验证返回的结果集
下面的操作可以在练习一的基础上继续操作,或者直接打开\Enterprise Library 4.1 HOL\CS\Validation\Labs\Lab02\Before目录下的ValidationHOL.sln项目文件。该Solution包含有两个项目,分别为ValidationHOL.BusinessLogic和ValidationHOL。
 
在上一节的练习中,仅仅一个错误的消息对话框,包含的信息过于简单。下面从ValidationResult中获取更多的详细信息。ValidationResults结果集中的每一个ValidationResult元素都包含了单一验证规则(Validation Rule)的验证失败信息,这些具体的信息可以显示在错误消息对话框中。
 
1. 打开MainForm.cs文件,添加如下命名空间的引用。
using System.Text;
using System.Globalization;
 
2. 更新MainForm.cs类中的acceptButton_Click方法,创建一个错误的StringBuilder,包含了所有ValidationResult元素中信息,代码如下。
private void acceptButton_Click(object sender, EventArgs e)
        {
            Customer customer = new Customer
            {
                FirstName = firstNameTextBox.Text,
                LastName = lastNameTextBox.Text,
                SSN = ssnTextBox.Text,
                Address = new Address
                {
                    StreetAddress = streetAddressTextBox.Text,
                    City = cityTextBox.Text,
                    State = stateComboBox.Text,
                    ZipCode = zipCodeTextBox.Text
                }
            };
 
            ValidationResults results = Validation.Validate(customer);
            if (!results.IsValid)
            {
                StringBuilder builder = new StringBuilder();
                builder.AppendLine("Customer is not valid:");
                foreach (ValidationResult result in results)
                {
                    builder.AppendLine(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            "{0}: {1}",
                            result.Key,
                            result.Message));
                }
                MessageBox.Show(
                    this,
                    builder.ToString(),
                    "Error",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }
 
            MessageBox.Show(
                this,
                "Processing customer '" + customer.FirstName + "'",
                "Working",
                MessageBoxButtons.OK,
                MessageBoxIcon.Information);
        }
上述代码使用ValidationResult元素的Key和Message属性,构建错误消息字符串。
 
3. 运行范例程序,检查是否正确遍历了ValidationResults结果集,且正确显示了错误信息。
在数据录入界面,不输入任何信息,如下图所示,点击Accept按钮,在弹出的错误消息对话框中,包含了具体的验证失败信息。
 
 
从上图中可以看出,仅仅显示了Customer类相关的错误信息,事实上,只需要录入Customer类的前3个属性(FirstName,LastName,SSN)就可以通过Validation rules的验证了,尽管Address类的相关属性也有validation的特性。这说明了嵌入类的验证不会自动触发,因此需要显式的调用,在下一节练习中介绍如何执行嵌入类的验证操作。
 

 
http://www.entlib.com专业ASP.NET电子商务平台小组,欢迎你继续访问Validation Application Block学习手册。
 
参考文档:
Validation Application Block Hands-On Labs for Enterprise Library
posted on 2010-09-15 09:59  vibratea  阅读(167)  评论(0编辑  收藏  举报