When testing my controller's actions the ModelState is always valid.
public class Product { public int Id { get; set; } [Required] [StringLength(10)] public string Name { get; set; } [Required] public string Description { get; set; } [Required] public decimal Price { get; set; } }
And my controller.
public class ProductController : Controller { [HttpPost] public ActionResult Create(Product product) { if (ModelState.IsValid) { // Do some creating logic... return RedirectToAction("Display"); } return View(product); } }
And test:
[Test] public TestInvalidProduct() { var product = new Product(); var controller = new ProductController(); controller.Create(product); //controller.ModelState.IsValid == true }
Why the modelState is valid when the product doesn't have a name, Description and price?
You get Model state not valid error when the server side validation of the model property has failed. So go to your action where you will find the following if condition that checks model state is valid: if (ModelState.
Below the Form, the ModelState. IsValid property is checked and if the Model is valid, then the value if the ViewBag object is displayed using Razor syntax in ASP.Net MVC.
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 .
The ModelState has two purposes: to store the value submitted to the server, and to store the validation errors associated with those values.
Validation happens when the posted data is bound to the view model. The view model is then passed into the controller. You are skipping part 1 and passing a view model straight into a controller.
You can manually validate a view model using
System.ComponentModel.DataAnnotations.Validator.TryValidateObject()
I have come across the same issue and while the accepted answer here did solve the "no-validation"-issue, it did leave me with a big negative aspect: it would throw an exception when there were validation errors instead of simply setting ModelState.Invalid
to false
.
I only tested this in Web Api 2 so I don't know what projects will have this available but there is a method ApiController.Validate(object)
which forces validation on the passed object and only sets the ModelState.IsValid
to false
. Additionally you'll also have to instantiate the Configuration
property.
Adding this code to my unit test allowed it to work:
userController.Configuration = new HttpConfiguration(); userController.Validate(addressInfo);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With