IValidatableObject实现model自定义验证
namespace: System.ComponentModel.DataAnnotations
Assembly: System.ComponentModel.DataAnnotations (in System.ComponentModel.DataAnnotations.dll)
Example:
public class IACUCRenewMembership : IValidatableObject { [DataMember] [Required(ErrorMessage="Membership Term Start Date is required.")] public DateTime MembershipStartDate { get; set; } [DataMember] [Required(ErrorMessage = "Membership Term End Date is required.")] public DateTime MembershipEndDate { get; set; } [DataMember] [Required(ErrorMessage = "Please select member.")] public string SelectedMemberList { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (MembershipStartDate >= MembershipEndDate) yield return new ValidationResult("Start Date can not be greater than End Date."); } }
Trigger validatation and return error messages in json format:
public ActionResult RenewMembership(IACUCMemberLogModel model) { var client = new IACUCServiceClient(); try { if (ModelState.IsValid) { // Perform business logic } else { return Json(ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage).ToList()); } } catch (Exception ex) { return Json(new List<string>() { ex.Message }); } finally { CleanUpServiceClient(client, client.InnerChannel); } }
扩展内容:
MVC Foolproof Validation
MVC Foolproof Validation aims to extend the Data Annotation validation provided in ASP.NET MVC. Initial efforts are focused on adding contingent validation.
参考链接
https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.ivalidatableobject(v=vs.110).aspx