【发布时间】:2012-07-26 11:52:56
【问题描述】:
我正在尝试对 ASP.NET MVC 项目使用流畅的验证。我正在尝试验证我的视图模型。
这是我的视图模型,
[Validator(typeof(ProductCreateValidator))]
public class ProductCreate
{
public string ProductCategory { get; set; }
public string ProductName { get; set; }
....
}
这是我的验证器类,
public class ProductCreateValidator : AbstractValidator<ProductCreate>
{
public ProductCreateValidator()
{
RuleFor(product => product.ProductCategory).NotNull();
RuleFor(product => product.ProductName).NotNull();
}
}
在我的控制器中,我正在检查我的 ModelState 是否有效,
[HttpPost]
public ActionResult Create(ProductCreate model)
{
/* This is a method in viewmodel that fills dropdownlists from db */
model.FillDropDownLists();
/* Here this is always valid */
if (ModelState.IsValid)
{
SaveProduct(model);
return RedirectToAction("Index");
}
// If we got this far, something failed, redisplay form
return View(model);
}
这就是我所拥有的。我的问题是 ModelState.IsValid 在我的视图模型完全为空时返回 true。我是否需要手动配置 Fluent 验证以便可以将模型错误添加到 ModalState ?
【问题讨论】:
标签: asp.net-mvc viewmodel fluentvalidation