Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is getting ModelState.IsValid functionality outside of a controller possible? [duplicate]

Tags:

c#

asp.net-mvc

Say I have a model that's annotated with [Required] fields etc in an MVC application.

It works great in the controller to just call ModelState.IsValid but say I'm not in the controller and would like to run similar checks elsewhere in my application on the model. Is it possible to somehow call this functionality another way?

class MyModel{
   [Required]
   public string Name{get;set;}
}

// Code elsewhere in app that isn't the controller
MyModel model = new MyModel();
//Can I run a modelstate.isvalid type check here on model?  Would return false if Name wasn't set
like image 308
Shaun Poore Avatar asked Jun 11 '13 14:06

Shaun Poore


People also ask

Why is my ModelState IsValid false?

That's because an error exists; ModelState. IsValid is false if any of the properties submitted have any error messages attached to them. What all of this means is that by setting up the validation in this manner, we allow MVC to just work the way it was designed.

What is ModelState IsValid method where we use it?

ModelState. IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process. In your example, the model that is being bound is of class type Encaissement .

How do you make a ModelState IsValid false?

AddModelError("Region", "Region is mandatory"); ModelState. IsValid will then return false.


1 Answers

Yes it is, using the TryValidateObject method on the Validator class in System.ComponentModel.DataAnnotations.

var results = new List<ValidationResult>();
var context = new ValidationContext(model, null, null);
if (!Validator.TryValidateObject(model, context, results))
{
    // results will contain all the failed validation errors.
}
like image 97
Jason Berkan Avatar answered Sep 20 '22 18:09

Jason Berkan