我有一个名为User
的课程和一个属性Name
public class User
{
[Required]
public string Name { get; set; }
}
我想验证它,如果有任何错误添加到控制器的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();
}
这些属性适用于UserViewModel
,但我想知道如何在不将其发布到操作的情况下验证类。
我该如何实现?
答案 0 :(得分:63)
您可以使用Validator来完成此任务。
var context = new ValidationContext(u, serviceProvider: null, items: null);
var validationResults = new List<ValidationResult>();
bool isValid = Validator.TryValidateObject(u, context, validationResults, true);
答案 1 :(得分:25)
我在Stack Overflow文档中做了一个条目,解释了如何执行此操作:
任何验证都需要一个上下文来提供有关正在验证的内容的一些信息。这可以包括各种信息,例如要验证的对象,一些属性,错误消息中显示的名称等。
ValidationContext vc = new ValidationContext(objectToValidate); // The simplest form of validation context. It contains only a reference to the object being validated.
创建上下文后,有多种方法可以进行验证。
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
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
要了解有关手动验证的更多信息,请参阅:
答案 2 :(得分:0)
由于该问题专门询问有关ASP.NET MVC的问题,因此可以在TryValidateObject
操作中使用Controller
。
您所需的方法重载为TryValidateModel(Object)
验证指定的模型实例。
如果模型验证成功,则返回true;否则,返回true。否则为假。
您修改后的源代码
[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();
}
答案 3 :(得分:0)
我写了一个包装纸,使它不那么笨拙。
用法:
var response = SimpleValidator.Validate(model);
var isValid = response.IsValid;
var messages = response.Results;
或者,如果您只关心检查有效性,则更加严格:
var isValid = SimpleValidator.IsModelValid(model);
完整来源:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Ether.Validation
{
public static class SimpleValidator
{
/// <summary>
/// Validate the model and return a response, which includes any validation messages and an IsValid bit.
/// </summary>
public static ValidationResponse Validate(object model)
{
var results = new List<ValidationResult>();
var context = new ValidationContext(model);
var isValid = Validator.TryValidateObject(model, context, results, true);
return new ValidationResponse()
{
IsValid = isValid,
Results = results
};
}
/// <summary>
/// Validate the model and return a bit indicating whether the model is valid or not.
/// </summary>
public static bool IsModelValid(object model)
{
var response = Validate(model);
return response.IsValid;
}
}
public class ValidationResponse
{
public List<ValidationResult> Results { get; set; }
public bool IsValid { get; set; }
public ValidationResponse()
{
Results = new List<ValidationResult>();
IsValid = false;
}
}
}
或者在以下要点:https://gist.github.com/kinetiq/faed1e3b2da4cca922896d1f7cdcc79b