asp.net mvc 模型验证-最舒服的验证方式

版权所有,禁止匿名转载;禁止商业使用。

在院子里发现 http://www.cnblogs.com/yangecnu/p/3759784.html 模型验证方法


1. 一般方法 繁琐, 无数的if else, 在炎炎夏天,我见过一个验证方法3000行代码的,还要改需求,想必您能了解作为coder当时的心情。


2. 使用第三方框架,功能过于繁琐,还得自己学习,没必要


3. Code Contract 不熟悉,貌似和第三方不同的是:MS提供的,先得高大上一点而已,本质一样


下面的方法,既简单,维护也很方便。代码涉及点:


1) 模型文件代码-添加验证规则,至于你想怎么添加,可以自定义Attribute,或者使用FCL中自带的(本例即是)


2)模型数据操作的Action-在需要验证的Actiond中注入属性或者controller或者全局也行


3)过滤器-添加错误捕捉,处理


维护时,只需要修改各个业务模型中每个字段的验证规则即可


模型建立:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace Model_Validation.Models
{
    public class User
    {
  [Required(ErrorMessage = "用户名不能为空")]
  public string UserName { get; set; }
  [RegularExpression("[a-z|A-Z|0-9]{6,20}", ErrorMessage = "密码位数太短")]
  public string UserPassword { get; set; }
  [DataType(DataType.EmailAddress, ErrorMessage = "邮件格式不正确")]
  public string EmailAddress { get; set; }
  [RangeAttribute(1, 1000, ErrorMessage = "评论长度1,1000")]
  public string Comments { get; set; }
    }
}
模型数据操作:
 [HttpPost, ModelValidationFilterAttribute]
  public JsonResult DoLogin(Models.User User)
  {
      return Json(new object(), JsonRequestBehavior.DenyGet);
  }
ModelValidationFilterAttribute:数据验证的过滤器
public class ModelValidationFilterAttribute : FilterAttribute,IActionFilter
{
  // Summary:
  // Called after the action method executes.
  //
  // Parameters:
  //   filterContext:
  // The filter context.
  public void OnActionExecuted(ActionExecutedContext filterContext) { }
  //
  // Summary:
  // Called before an action method executes.
  //
  // Parameters:
  //   filterContext:
  // The filter context.
  public void OnActionExecuting(ActionExecutingContext filterContext)
  {
    var _MS = ((Controller)filterContext.Controller).ModelState;
    if (!_MS.IsValid)
    {
      var _FirstErrorField = _MS.FirstOrDefault();
      string strHtmlId = _FirstErrorField.Key;
      string strErrorMessage = _FirstErrorField.Value.Errors.FirstOrDefault().ErrorMessage;//这个数据你想怎么给JS都行.
    }
  }
}


0 0