检查模型在控制器之外是否有效 [英] Check if Model is valid outside of Controller
本文介绍了检查模型在控制器之外是否有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个辅助类,它传递了一个值数组,然后从我的模型传递给一个新类.我如何验证给这个类的所有值都有效?换句话说,我如何在非控制器类中使用 ModelState 的功能.
I have a helper class that is passed an array of values that is then passed to a new class from my Model. How do I verify that all the values given to this class are valid? In other words, how do I use the functionality of ModelState within a non-controller class.
来自控制器:
public ActionResult PassData()
{
Customer customer = new Customer();
string[] data = Monkey.RetrieveData();
bool isvalid = ModelHelper.CreateCustomer(data, out customer);
}
来自帮手:
public bool CreateCustomer(string[] data)
{
Customter outCustomer = new Customer();
//put the data in the outCustomer var
//??? Check that it's valid
}
推荐答案
您可以在 ASP.NET 上下文之外使用数据注释验证:
You could use the data annotations validation outside of an ASP.NET context:
public bool CreateCustomer(string[] data, out Customer customer)
{
customer = new Customer();
// put the data in the customer var
var context = new ValidationContext(customer, serviceProvider: null, items: null);
var results = new List<ValidationResult>();
return Validator.TryValidateObject(customer, context, results, true);
}
这篇关于检查模型在控制器之外是否有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文