3
我想在ASP.NET MVC项目中使用流畅的验证。我试图验证我的视图模型。ASP.NET MVC ModelState始终与Fluent验证有效
这是我的视图模型,
[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
当我的viewmodel是完全空的。我是否需要手动配置Fluent验证,以便可以将模型错误添加到ModalState中?
非常多。关于viewmodels,我在我看来有几个下拉列表,我希望它们从db中填充。我可以采用什么方法来填补我目前的替代方案? – 2012-07-26 12:16:50
我简单的方法是让控制器调用一个主持人。演示者有责任调用数据库来创建视图模型和填充列表。在更复杂的情况下,您也可以使用映射器从模型或视图模型的模型创建视图模型。在所有情况下,视图模型只应了解自己,而遵循只有原始类型引用的POCO模式。 – Samuel 2012-07-31 01:20:02