如何手动验证带有属性的模型? [英] 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.
我该怎么做?
推荐答案
您可以使用 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屋!
查看全文