Manually references ModelState validation

I am using the first ASP.NET MVC 3 code, and I have added validation data annotations for my models. Here is 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; } } 

On my website I have a multi-step process of creating a new product - step 1 you enter the product information, step 2 - other information, etc. Between each step, I store each object (i.e. the Product object) in the session, so the user can return to this stage of the process and change the entered data.

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

The final stage is the confirmation screen, after which the product is created in the database. However, since the user can jump between stages, I need to check the objects (Product and some others) to make sure that they performed the data correctly.

Is there a way to programmatically call a ModelState check on an object with data annotations? I do not want to go through each property of the object and perform a manual check.

I am open to suggestions on how to improve this process if it simplifies the use of the ASP.NET MVC 3 model validation functions.

+50
c # asp.net-mvc asp.net-mvc-3 asp.net-mvc-validation
Jun 15 2018-11-15T00:
source share
3 answers

You can call the ValidateModel method in the Controller action (

+66
Jun 15 2018-11-15T00:
source share

You can use ValidateModel or TryValidateModel in the control area.

When a model is validated, all validators for all properties have at least one form input associated with the model property. ValidateModel is similar to the TryValidateModel method, except that the TryValidateModel method does not throw an InvalidOperationException exception if the model is not validated.

ValidateModel - Throws an exception if the model is invalid.

TryValidateModel - Returns a bool value indicating whether the model is valid.

If you check the list of models one by one, you need to reset ModelState for each iteration by calling ModelState.Clear() .

MSDN Link

+33
Nov 15 '13 at 7:21
source share

I found that this works and works exactly as expected .. showing a ValidationSummary for the newly received object using the GET action method ... before any POST

 Me.TryValidateModel(MyCompany.OrderModel) 
+2
Sep 06 '13 at 18:50
source share



All Articles