技术开发 频道

MVC框架开发Web论坛之另类表单校验篇

  列表2–RuleViolation.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcValidation
{
    
public class RuleViolation
    {
        
public string PropertyName { get; private set; }

        
public object PropertyValue { get; private set; }

        
public string ErrorMessage { get; private set; }

        
public RuleViolation(string propertyName, object propertyValue, string errorMessage)
        {
            
this.PropertyName = propertyName;
            
this.PropertyValue = propertyValue;
            
this.ErrorMessage = errorMessage;
        }

    }
}

  即使存在一条规则被破坏的情况,也会引发一个RuleViolationException异常。列表3中提供了这个特别的异常类的实现代码。
列表3–RuleViolationException.cs
 

using System;
using System.Collections.Generic;

namespace MvcValidation
{
    
public class RuleViolationException : Exception
    {
        
public RuleViolationException(string message, List<RuleViolation> validationIssues)
            :
base(message)
        {
            
this.ValidationIssues = validationIssues;
        }

        
public List<RuleViolation> ValidationIssues { get; private set; }
    }
}

  最后请注意,该Validation类是一个工具类,它暴露了一个名字为UpdateModelStateWithViolations()的方法。这个方法负责把所有的校验规则复制到一个控制器类的ModelState数据中。列表3中提供了这个校验类的实现代码。

0
相关文章