检查模型在Controller之外是否有效

我有一个辅助类,它传递一个值数组,然后从我的模型传递给一个新类。 如何validation给予此类的所有值是否有效? 换句话说,如何在非控制器类中使用ModelState的function。

从控制器:

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上下文之外使用数据注释validation:

 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(); return Validator.TryValidateObject(customer, context, results, true); } 

不要在控制器之外使用ModelState。 我看不出Monkey.RetrieveData()的作用,但一般情况下我不会传递a)HTTPRequest中的普通数据和b)像字符串数组这样的无类型数据到你的后端。 让web框架检查在后端使用的incomming数据和instanciate类型类。 请注意,如果手动应用数据,则必须手动完成HTML注入(XSS脚本等)的检查。

而是使用模型绑定器等,并将类型化数据(例如,Customer类实例)传递给后端。 来自Scott Gu的一篇较早的post显示了MVC1: http ://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting- scenarios.aspx

在您的示例中,让MVC的模型绑定创建您的客户并应用所需的字段值(请参阅上面的链接,该模式的工作原理)。 然后,将您的Customer实例提供给后端,根据您键入的Customer实例(例如,手动或使用数据注释)进行其他validation检查。