Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually invoking ModelState validation

I'm using ASP.NET MVC 3 code-first and I have added validation data annotations to my models. Here's an example model:

public class Product {     public int ProductId { get; set; }      [Required(ErrorMessage = "Please enter a name")]     public string Name { get; set; }      [Required(ErrorMessage = "Please enter a description")]     [DataType(DataType.MultilineText)]     public string Description { get; set; }      [Required(ErrorMessage = "Please provide a logo")]     public string Logo { get; set; } } 

In my website I have a multi-step process to create a new product - step 1 you enter product details, step 2 other information etc. Between each step I'm storing each object (i.e. a Product object) in the Session, so the user can go back to that stage of the process and amend the data they entered.

On each screen I have client-side validation working with the new jQuery validation fine.

The final stage is a confirm screen after which the product gets created in the database. However because the user can jump between stages, I need to validate the objects (Product and some others) to check that they have completed the data correctly.

Is there any way to programatically call the ModelState validation on an object that has data annotations? I don't want to have to go through each property on the object and do manual validation.

I'm open to suggestions of how to improve this process if it makes it easier to use the model validation features of ASP.NET MVC 3.

like image 454
Sam Huggill Avatar asked Jun 15 '11 15:06

Sam Huggill


People also ask

Why is my ModelState IsValid false?

IsValid is false now. 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.


1 Answers

You can call the ValidateModel method within a Controller action (documentation here).

like image 144
Steve Avatar answered Sep 22 '22 08:09

Steve