检查型号是控制器的有效外 [英] Check if Model is valid outside of Controller

查看:70
本文介绍了检查型号是控制器的有效外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个传递,然后传递到一个新的类从我的模型值的数组一个辅助类。我如何验证给这个类中的所有值都有效吗?换句话说,我怎么使用的ModelState的功能非控制器类中。

从控制器:

 公众的ActionResult PassData()
{
    客户客户=新客户();
    字符串[]数据= Monkey.RetrieveData();
    BOOL的isValid = ModelHelper.CreateCustomer(数据,出客户);
}

从助手:

 公共BOOL CreateCustomer(字符串[]数据)
{
    Customter outCustomer =新客户();
    //把数据在outCustomer VAR
    //?检查它是有效的}


解决方案

您可以使用数据注释验证的ASP.NET环境之外:

 公共BOOL CreateCustomer(字符串[]的数据,从客户的客户)
{
    客户=新客户();
    //把数据在客户VAR    VAR语境=新ValidationContext(客户的ServiceProvider:空,项目:NULL);
    VAR的结果=新的List<&为ValidationResult GT;();    返回Validator.TryValidateObject(客户,环境,结果,真正的);
}

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.

From the controller:

public ActionResult PassData()
{
    Customer customer = new Customer();
    string[] data = Monkey.RetrieveData();
    bool isvalid = ModelHelper.CreateCustomer(data, out customer);
}

From the helper:

public bool CreateCustomer(string[] data)
{
    Customter outCustomer = new Customer();
    //put the data in the outCustomer var
    //??? Check that it's valid

}

解决方案

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屋!

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