如何手动validation具有属性的模型?
我有一个名为User
的类和一个属性Name
public class User { [Required] public string Name { get; set; } }
我想validation它,如果有任何错误添加到控制器的ModelState
或实例化另一个模型状态…
[HttpPost] public ActionResult NewUser(UserViewModel userVM) { User u = new User(); u.Name = null; /* something */ // assume userVM is valid // I want the following to be false because `user.Name` is null if (ModelState.IsValid) { TempData["NewUserCreated"] = "New user created sucessfully"; return RedirectToAction("Index"); } return View(); }
这些属性适用于UserViewModel
,但我想知道如何在不将其发布到操作的情况下validation类。
我怎么能做到这一点?
您可以使用Validator来完成此任务。
var context = new ValidationContext(u, serviceProvider: null, items: null); var validationResults = new List(); bool isValid = Validator.TryValidateObject(u, context, validationResults, true);
我在Stack Overflow Documentation中做了一个条目,解释了如何执行此操作:
validation上下文
任何validation都需要一个上下文来提供有关正在validation的内容的一些信息。 这可以包括各种信息,例如要validation的对象,一些属性,错误消息中显示的名称等。
ValidationContext vc = new ValidationContext(objectToValidate); // The simplest form of validation context. It contains only a reference to the object being validated.
创建上下文后,有多种方法可以进行validation。
validation对象及其所有属性
ICollection results = new List (); // Will contain the results of the validation bool isValid = Validator.TryValidateObject(objectToValidate, vc, results, true); // Validates the object and its properties using the previously created context. // The variable isValid will be true if everything is valid // The results variable contains the results of the validation
validation对象的属性
ICollection results = new List (); // Will contain the results of the validation bool isValid = Validator.TryValidatePropery(objectToValidate.PropertyToValidate, vc, results, true); // Validates the property using the previously created context. // The variable isValid will be true if everything is valid // The results variable contains the results of the validation
和更多
要了解有关手动validation的更多信息,请
- ValidationContext类文档
- validation器类文档