Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a validation error in MVC for a view model with multiple properties?

Tags:

If I have a view model that looks something like this:

public class Car  {       Wheel CarWheel {get;set;}      Body CarBody {get;set;}  } 

And my Wheel and Body classes look something like this:

public class Wheel {     int Number {get;set;}     string WheelType {get;set;} }  public class Body {     int Number {get;set;}     string BodyType {get;set;} } 

And I want to add a model error for the wheel number being less than 1:

ModelState.AddModelError(???, "Error! You must have at least one wheel to avoid abrasion on your bottom"); 

How do I specify that the error is specifically with the Wheel class, and not the Body class?

like image 209
John Zumbrum Avatar asked Aug 20 '12 23:08

John Zumbrum


People also ask

Does attributes can be used for data validation in MVC?

Answer is "DataAnnotations"

Which component of MVC controller can be used to find dictionary of validation error?

ASP.NET MVC: ValidationSummary The ValidationSummary() extension method displays a summary of all validation errors on a web page as an unordered list element. It can also be used to display custom error messages.


1 Answers

To specify that the error is on the CarWheel version of Number and not CarBody, you'll need to "namespace" the value for the property name in the same way you would to get or set that property's value:

ModelState.AddModelError("CarWheel.Number", "Error! You must have at least one wheel to avoid abrasion on your bottom"); 
like image 183
Bryan Avatar answered Sep 20 '22 02:09

Bryan