ViewModel
public class ViewModel { [Required(ErrorMessage="标题不能为空")] public string Title { get; set; } public string Name { get; set; } }
后台验证代码
public async Task<ActionResult> Save(ViewModel vm) { var validationContext = new ValidationContext(vm); var results = new List<ValidationResult>(); var isValid = Validator.TryValidateObject(vm, validationContext, results, true); if (!isValid) { return Json(new { Result = false, Msg = results.Select(x => x.ErrorMessage).FirstOrDefault() }); } return Json(new { Result = true, Msg = "成功!" }); }
前台调用:
$.ajax({ type: "post", url: "/home/save", data: "title=&name=11222332", dataType:"json", success: function(data) { alert(data.Msg); } });
原文地址:http://www.cnblogs.com/dudu/p/annotation-based-validation.html#3100481