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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12046423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 20:13:15  来源:igfitidea点击:

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

c#asp.net-mvc

提问by John Zumbrum

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:

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

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:

我想为车轮编号小于 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?

我如何指定错误是专门针对 Wheel 类而不是 Body 类的?

采纳答案by Bryan

To specify that the error is on the CarWheelversion of Numberand 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:

要指定错误发生在和 not的CarWheel版本上,您需要以与获取或设置该属性的值相同的方式“命名空间”属性名称的值:NumberCarBody

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

回答by Sender

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");

回答by chris

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

Bryan 的回答,或者您可以尝试使用数据注释。

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

range 属性应该适合您,或者您可以根据需要自行编写。