Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to update ModelState.IsValid manually?

I would like to use the built-in validation features as far as possible. I would also like to use the same model for CRUD methods.

However, as a drop down list cannot be done using the standard pattern, I have to validate it manually. In the post back method, I would like to just validate the drop down list and add this result to ModelState so that I don't have to validate all the other parameters which are done with Data Annotation. Is it possible to achieve this?

I may be mistaken about the drop down list, but from what I read, the Html object name for a drop down list cannot be the same as the property in the Model in order for the selected value to be set correctly. Is it still possible to use Data Annotation with this workaround?

Thanks.

like image 853
Old Geezer Avatar asked Apr 24 '12 10:04

Old Geezer


2 Answers

You can use the addModelError

ModelState.AddModelError(key,message) 

when you use that, it will invalidate the ModelState so isValid will return false.


Update
after seeing the comment to @Pieter's answer

If you want to exclude an element from affecting the isValid() result, you can use the ModelState.Remove(field) method before calling isValid().

like image 114
Gabriele Petrioli Avatar answered Sep 19 '22 15:09

Gabriele Petrioli


Another option is to inherit IValidatableObject in your model. Implement its Validate method and you can leave all other validation in place and write whatever code you want in this method. Note: you return an empty IEnumerable<ValidationResult> to indicate there were no errors.

public class Class1 : IValidatableObject {     public int val1 { get; set; }     public int val2 { get; set; }      public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)     {         var errors = new List<ValidationResult>();         if (val1 < 0)         {             errors.Add(new ValidationResult("val1 can't be negative", new List<string> { "val2" }));         }         if (val2 < 0)         {             errors.Add(new ValidationResult("val2 can't be negative", new List<string> { "val2" }));         }         return errors;     } } 

EDIT: After re-reading the question I don't think this applicable to this case, but I'm leaving the answer here in case it helps someone else.

like image 35
Tim Coker Avatar answered Sep 18 '22 15:09

Tim Coker