22

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?

3 Answers 3

33

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");
Sign up to request clarification or add additional context in comments.

Comments

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

OR

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

1 Comment

If you are using the standard Html.TextBoxFor, etc. generators, this will not work. The Naming convention there is Model.Property.
1

Bryan's answer or you could try using data annotations.

The range attribute should work for you or you could write your own if need be.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.