如果我有一个看起来像这样的视图模型:
public class Car
{
Wheel CarWheel {get;set;}
Body CarBody {get;set;}
}
我的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;}
}
我想为车轮编号小于1添加模型错误:
ModelState.AddModelError(???, "Error! You must have at least one wheel to avoid abrasion on your bottom");
如何指定错误特定于Wheel类,而不是Body类?
答案 0 :(得分:30)
要指定错误位于CarWheel
版本的Number
而不是CarBody
,您需要以与命名方式相同的方式“命名”属性名称的值会获得或设置该属性的值:
ModelState.AddModelError("CarWheel.Number", "Error! You must have at least one wheel to avoid abrasion on your bottom");
答案 1 :(得分: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");
答案 2 :(得分:1)
Bryan的回答或您可以尝试使用数据注释。
范围属性应该适合您,或者如果需要,您可以编写自己的属性。