James Santiago
James Santiago

Reputation: 3062

Check if Model is valid outside of Controller

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

}

Upvotes: 21

Views: 13161

Answers (2)

Marc
Marc

Reputation: 4813

Don't use ModelState outside of a controller. I can't see what Monkey.RetrieveData() does but in general I would not pass a) plain data from the HTTPRequest and b) untyped data like string-arrays to your backend. Let the web-framework check the incomming data and instanciate typed classes to use in the backend. Note that checking for HTML injection (XSS scripting etc.) must be done manually if you apply your data manually.

Instead use model-binders etc. and pass typed data (eg. Customer class instances) to your backend. There is an older post from Scott Gu that shows this for MVC1: http://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting-scenarios.aspx

In your example let the model binding of MVC create your customer and apply the field values required (see link above how that pattern works). You then give your Customer instance to your backend where additional validation checks can be done based on your typed Customer instance (eg. manually or with data annotations).

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039278

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

Upvotes: 40

Related Questions