Bru*_*oLM 36 c# asp.net-mvc asp.net-mvc-4
我有一个叫做User
属性的类Name
public class User
{
[Required]
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我想验证它,如果有任何错误添加到控制器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();
}
Run Code Online (Sandbox Code Playgroud)
这些属性适用于UserViewModel
,但我想知道如何在不将其发布到操作的情况下验证类.
我怎么能做到这一点?
Jam*_*ago 68
您可以使用Validator来完成此任务.
var context = new ValidationContext(u, serviceProvider: null, items: null);
var validationResults = new List<ValidationResult>();
bool isValid = Validator.TryValidateObject(u, context, validationResults, true);
Run Code Online (Sandbox Code Playgroud)
Max*_*ime 27
我在Stack Overflow Documentation中做了一个条目,解释了如何执行此操作:
任何验证都需要一个上下文来提供有关正在验证的内容的一些信息.这可以包括各种信息,例如要验证的对象,一些属性,错误消息中显示的名称等.
ValidationContext vc = new ValidationContext(objectToValidate); // The simplest form of validation context. It contains only a reference to the object being validated.
Run Code Online (Sandbox Code Playgroud)
创建上下文后,有多种方法可以进行验证.
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
要了解有关手动验证的更多信息,请
Bri*_*Kay 10
我编写了一个包装器,以使其使用起来不那么笨重。
用法:
var response = SimpleValidator.Validate(model);
var isValid = response.IsValid;
var messages = response.Results;
Run Code Online (Sandbox Code Playgroud)
或者,如果您只关心检查有效性,那就更严格了:
var isValid = SimpleValidator.IsModelValid(model);
Run Code Online (Sandbox Code Playgroud)
完整来源:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
或者在这个要点:https://gist.github.com/kinetiq/faed1e3b2da4cca922896d1f7cdcc79b
由于问题是专门询问 ASP.NET MVC,因此您可以使用TryValidateObject
insideController
操作。
您想要的方法重载是 TryValidateModel(Object)
验证指定的模型实例。
如果模型验证成功,则返回 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();
}
Run Code Online (Sandbox Code Playgroud)