是否可以在控制器外部获取ModelState.IsValid功能? [英] Is getting ModelState.IsValid functionality outside of a controller possible?

查看:80
本文介绍了是否可以在控制器外部获取ModelState.IsValid功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个在MVC应用程序中带有[必填]字段等注释的模型.

Say I have a model that's annotated with [Required] fields etc in an MVC application.

在控制器中仅调用ModelState.IsValid效果很好,但是说我不在控制器中,并且希望在模型的应用程序中的其他地方运行类似的检查.是否可以以其他方式调用此功能?

It works great in the controller to just call ModelState.IsValid but say I'm not in the controller and would like to run similar checks elsewhere in my application on the model. Is it possible to somehow call this functionality another way?

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方法.

Yes it is, using the TryValidateObject method on the Validator class in System.ComponentModel.DataAnnotations.

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

这篇关于是否可以在控制器外部获取ModelState.IsValid功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆