如何手动验证具有属性的模型? [英] How to manually validate a model with attributes?
本文介绍了如何手动验证具有属性的模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为 User
的类和一个属性 Name
I have a class called User
and a property Name
public class User
{
[Required]
public string Name { get; set; }
}
我想验证它,如果有任何错误添加到控制器的 ModelState
或实例化另一个模型状态...
And I want to validate it, and if there are any errors add to the controller's ModelState
or instantiate another 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
,但我想知道如何在不将其发布到操作的情况下验证类.
The attributes works for UserViewModel
, but I want to know how to validate a class without posting it to an action.
我怎样才能做到这一点?
How can I accomplish that?
推荐答案
您可以使用 Validator 来完成此操作.
You can use Validator to accomplish this.
var context = new ValidationContext(u, serviceProvider: null, items: null);
var validationResults = new List<ValidationResult>();
bool isValid = Validator.TryValidateObject(u, context, validationResults, true);
这篇关于如何手动验证具有属性的模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文