是否可以在控制器之外获得ModelState.IsValidfunction?

假设我在MVC应用程序中有一个用[Required]字段等注释的模型。

它在控制器中工作得很好,只需调用ModelState.IsValid,但是我说我不在控制器中,并且想在模型上的应用程序的其他地方运行类似的检查。 有可能以某种方式调用此function吗?

class MyModel{ [Required] public string Name{get;set;} } // Code elsewhere in app that isn't the controller MyModel model = new MyModel(); //Can I run a modelstate.isvalid type check here on model? Would return false if Name wasn't set 

是的,使用System.ComponentModel.DataAnnotationsValidator类上的TryValidateObject方法。

 var results = new List(); var context = new ValidationContext(model, null, null); if (!Validator.TryValidateObject(model, context, results)) { // results will contain all the failed validation errors. }