如何在MVC中为具有多个属性的视图模型添加验证错误?

Joh*_*rum 22 c# asp.net-mvc

如果我有一个看起来像这样的视图模型:

public class Car

{

     Wheel CarWheel {get;set;}
     Body CarBody {get;set;}

}
Run Code Online (Sandbox Code Playgroud)

而我的Wheel and Body类看起来像这样:

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

public class Body
{
    int Number {get;set;}
    string BodyType {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

我想为车轮编号小于1添加模型错误:

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

如何指定错误特定于Wheel类,而不是Body类?

Bry*_*yan 31

要指定错误是对CarWheel的版本Number,而不是CarBody,你需要以同样的方式来"命名"为属性名称的值,你需要获取或设置该属性的值:

ModelState.AddModelError("CarWheel.Number", "Error! You must have at least one wheel to avoid abrasion on your bottom");
Run Code Online (Sandbox Code Playgroud)