C# 如何手动验证具有属性的模型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17138749/
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-10 08:41:36  来源:igfitidea点击:

How to manually validate a model with attributes?

c#asp.net-mvcasp.net-mvc-4

提问by BrunoLM

I have a class called Userand a property Name

我有一个班级User和一个属性Name

public class User
{
    [Required]
    public string Name { get; set; }
}

And I want to validate it, and if there are any errors add to the controller's ModelStateor instantiate another modelstate...

我想验证它,如果有任何错误添加到控制器ModelState或实例化另一个模型状态...

[HttpPost]
public ActionResult NewUser(UserViewModel userVM)
{
    User u = new User();
    u.Name = null;

    /* something */

    // assume userVM is valid
    // I want the following to be false because `user.Name` is null
    if (ModelState.IsValid)
    {
        TempData["NewUserCreated"] = "New user created sucessfully";

        return RedirectToAction("Index");
    }

    return View();
}

The attributes works for UserViewModel, but I want to know how to validate a class without posting it to an action.

这些属性适用于UserViewModel,但我想知道如何在不将其发布到操作的情况下验证类。

How can I accomplish that?

我怎样才能做到这一点?

采纳答案by James Santiago

You can use Validatorto accomplish this.

您可以使用Validator来完成此操作。

var context = new ValidationContext(u, serviceProvider: null, items: null);
var validationResults = new List<ValidationResult>();

bool isValid = Validator.TryValidateObject(u, context, validationResults, true);

回答by Maxime

I made an entry in the Stack Overflow Documentation explaining how to do this:

我在 Stack Overflow 文档中做了一个条目,解释了如何做到这一点:

Validation Context

验证上下文

Any validation needs a context to give some information about what is being validated. This can include various information such as the object to be validated, some properties, the name to display in the error message, etc.

任何验证都需要一个上下文来提供有关正在验证的内容的一些信息。这可以包括各种信息,例如要验证的对象、某些属性、要在错误消息中显示的名称等。

ValidationContext vc = new ValidationContext(objectToValidate); // The simplest form of validation context. It contains only a reference to the object being validated.

Once the context is created, there are multiple ways of doing validation.

一旦创建了上下文,就可以通过多种方式进行验证。

Validate an Object and All of its Properties

验证对象及其所有属性

ICollection<ValidationResult> results = new List<ValidationResult>(); // Will contain the results of the validation
bool isValid = Validator.TryValidateObject(objectToValidate, vc, results, true); // Validates the object and its properties using the previously created context.
// The variable isValid will be true if everything is valid
// The results variable contains the results of the validation

Validate a Property of an Object

验证对象的属性

ICollection<ValidationResult> results = new List<ValidationResult>(); // Will contain the results of the validation
bool isValid = Validator.TryValidatePropery(objectToValidate.PropertyToValidate, vc, results, true); // Validates the property using the previously created context.
// The variable isValid will be true if everything is valid
// The results variable contains the results of the validation

And More

和更多

To learn more about manual validation see:

要了解有关手动验证的更多信息,请参阅:

回答by WoIIe

Since the question is asking specifically about ASP.NET MVC, you can use the TryValidateObjectinside your Controlleraction.

由于问题是专门询问 ASP.NET MVC,因此您可以使用TryValidateObjectinsideController操作。

Your desired method overload is TryValidateModel(Object)

您想要的方法重载是 TryValidateModel(Object)

Validates the specified model instance.

Returns true if the model validation is successful; otherwise false.

验证指定的模型实例。

如果模型验证成功,则返回 true;否则为假。

Your modified source code

您修改后的源代码

[HttpPost]
public ActionResult NewUser(UserViewModel userVM)
{
    User u = new User();
    u.Name = null;

    if (this.TryValidateObject(u))
    {
        TempData["NewUserCreated"] = "New user created sucessfully";
        return RedirectToAction("Index");
    }

    return View();
}