常常看到這個代碼css
在controller 中寫入驗證模型,每一個須要驗證的action 都寫….. ,就問你煩不煩~html
能夠利用 ASP.NET MVC 的 action 攔截機制 自動處理。ajax
1 新建驗證模型mvc
添加 using System.ComponentModel.DataAnnotations; 引用ide
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 攔截ui
ModelValidateAttributespa
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); } } |
全局過濾中註冊code
public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); filters.Add(new JsonRequestBehaviorAttribute()); filters.Add(new ModelValidateAttribute()); } } |
controller 裏的 驗證就能夠去掉了orm
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:http://benfoster.io/blog/automatic-modelstate-validation-in-aspnet-mvchtm