经常看到这个代码
在controller 中写入验证模型,每个需要验证的action 都写….. ,就问你烦不烦~
可以利用 ASP.NET MVC 的 action 拦截机制 自动处理。
1 新建验证模型
添加 using System.ComponentModel.DataAnnotations; 引用
public class Student { public int Id { get; set; } [Required(ErrorMessage="姓名不能为空")] public string Name { get; set; } [Range(0,150,ErrorMessage="年龄不合法")] public int Age { get; set; } } |
2 新建一个 action 拦截
ModelValidateAttribute
public class ModelValidateAttribute:ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { var viewData = filterContext.Controller.ViewData; if (!viewData.ModelState.IsValid) { var errorMessage = ""; foreach (var key in viewData.ModelState.Keys) { var state = viewData.ModelState[key]; if (state.Errors.Any()) { errorMessage = state.Errors.First().ErrorMessage; break; } } // ajax 直接返回错误验证结果 if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest()) { filterContext.Result = new JsonResult { Data = new { success = false, error = errorMessage }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } else { //filterContext.Result = new ViewResult //{ // ViewData = viewData, // TempData = filterContext.Controller.TempData //}; filterContext.Result = new ContentResult() { Content = errorMessage }; // throw new Exception(string.Format("参数异常:{0}",errorMessage)); } } base.OnActionExecuting(filterContext); } } |
全局过滤中注册
public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); filters.Add(new JsonRequestBehaviorAttribute()); } } |
controller 里的 验证就可以去掉了
public class StudentController : Controller { // // GET: /Student/ public ActionResult Index() { return View(); } public JsonResult Create(Student model) { //if (ModelState.IsValid) //{ // return Json(new { success = true, message = "成功" }); //} //else { // var error = ""; // foreach (var key in ModelState.Keys) // { // var state = ModelState[key]; // if (state.Errors.Any()) // { // error = state.Errors.First().ErrorMessage; // break; // } // } // return Json(new { success = false, message = error }); //} return Json(new { success = true, message = "成功" }); } public ActionResult GetStudent(Student model) { return View(); } } |
参考bolg: