【问题标题】:Check if Model is valid outside of Controller检查模型在控制器之外是否有效
【发布时间】:2012-06-24 09:48:40
【问题描述】:

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

从控制器:

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

}

【问题讨论】:

    标签: c# asp.net-mvc-3 model helper


    【解决方案1】:

    您可以在 ASP.NET 上下文之外使用数据注释验证:

    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);
    }
    

    【讨论】:

    • 不幸的是,此验证不会通过任何复杂的子对象或集合进行递归。 Validator.TryValidateObject(...) 只是立即进行属性和字段验证,并称之为一天,而不是在 MVC 世界中的控制器中发生的模型绑定上的验证,它遍历整个对象图。
    【解决方案2】:

    不要在控制器之外使用 ModelState。我看不到 Monkey.RetrieveData() 做了什么,但一般来说,我不会将 a) 来自 HTTPRequest 的纯数据和 b) 无类型数据(如字符串数组)传递到您的后端。让 web 框架检查传入的数据并实例化类型的类以在后端使用。请注意,如果您手动应用数据,则必须手动检查 HTML 注入(XSS 脚本等)。

    改为使用模型绑定器等并将类型数据(例如客户类实例)传递到您的后端。 Scott Gu 有一篇较早的帖子显示了 MVC1:http://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting-scenarios.aspx

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

    【讨论】:

      猜你喜欢
      • 2013-12-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-08
      • 2021-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多