ViewModel
public class ViewModel { [Required (errormessage= title cannot be null ")] public string Title {get; set;} public string Name {get; set;} }
Background validation Code
Public async task<actionresult> Save (ViewModel vm) { var validationcontext = new Validationcontext (VM); C7/>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 = "Success! " }); }
Foreground call:
$.ajax ({ type: "Post", URL: "/home/save", data: "title=&name=11222332", dataType: "JSON", Success:function (data) { alert (data). (MSG); } });
Original address: http://www.cnblogs.com/dudu/p/annotation-based-validation.html#3100481
"Reprint" C # Background declarative validation, away from if validation