Enterprise Library 4.1 Validation Block 快速使用图文笔记

验证块使用C#在服务端对数据进行验证。

一,下载并安装好Enterprise Library 4.1

二,新建一个Web应用程序

三,右键点击Web.Config 文件 使用 Edit Enterprise Library Configuration 可以编辑Web.Config,添加一个验证程序块。

Enterprise Library 4.1 Validation Block 快速使用图文笔记_第1张图片

再为配置文件添加一个configuration Sources 配置,来设置存放“配置信息文件”的位置

删除configuration Sources 默认的System 配置节点,并添加一个新的“文件配置节点File Configuration Source”,

修改SelectedSource 属性值,使其成为默认配置文件。

Enterprise Library 4.1 Validation Block 快速使用图文笔记_第2张图片

配置文件配置节点的File属性,选择一个配置文件,这个文件就是用于存放验证信息的文件了

Enterprise Library 4.1 Validation Block 快速使用图文笔记_第3张图片

右键点击验证节点,添加类型,并通过Load From File 按钮,选择加载~将要验证的类所在的Dll文件,之后选择要验证的类,如下图所示

Enterprise Library 4.1 Validation Block 快速使用图文笔记_第4张图片

选择一个要验证的类

Enterprise Library 4.1 Validation Block 快速使用图文笔记_第5张图片

右键“Rule Set ”节点添加此类的验证成员

Enterprise Library 4.1 Validation Block 快速使用图文笔记_第6张图片 Enterprise Library 4.1 Validation Block 快速使用图文笔记_第7张图片

为类成员添加验证规则如下图

Enterprise Library 4.1 Validation Block 快速使用图文笔记_第8张图片

配置验证规则的属性

Enterprise Library 4.1 Validation Block 快速使用图文笔记_第9张图片

设置此类的默认规则为Rule Set 也就是刚才添加的那个,也可以添加多个,选择其中的一个

Enterprise Library 4.1 Validation Block 快速使用图文笔记_第10张图片

 

四,添加程序集引用

Enterprise Library 4.1 Validation Block 快速使用图文笔记_第11张图片

五,编写代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Practices.EnterpriseLibrary.Validation;

namespace ValidationBlock
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            MyClass myClass = new MyClass();
            myClass.MyAddress = this.TextBox1.Text;
            myClass.MyName = this.TextBox2.Text;

            ValidationResults results = Validation.Validate<MyClass>(myClass);

            if (!results.IsValid)
            {
                foreach (ValidationResult vr in results)
                {
                    Response.Write(string.Format("错误位置:{0};原因:{1}<br>", vr.Key, vr.Message));
                }
            }
        }
    }
}

 

 

 

六,添加生成事件脚本,复制Config,没有Config会报错

copy "$(ProjectDir)\*.config" "$(TargetDir)"

Enterprise Library 4.1 Validation Block 快速使用图文笔记_第12张图片

七,运行查看结果

Enterprise Library 4.1 Validation Block 快速使用图文笔记_第13张图片
示例源码下载:EL41Sample.rar
Enterprise Library 4.1 目录:Enterprise Library 4.1 快速使用图文笔记 目录

你可能感兴趣的:(Web,UI,Microsoft,脚本,LINQ)