asp.net-mvc – ASP.NET MVC ModelState始终对Fluent验证有效
发布时间:2020-12-16 06:31:30 所属栏目:asp.Net 来源:网络整理
导读:我试图使用ASP.NET MVC项目的流畅验证.我正在尝试验证我的视图模型. 这是我的viewmodel, [Validator(typeof(ProductCreateValidator))]public class ProductCreate{ public string ProductCategory { get; set; } public string ProductName { get; set; } .
我试图使用ASP.NET MVC项目的流畅验证.我正在尝试验证我的视图模型.
这是我的viewmodel, [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在我的viewmodel完全为空时返回true.我是否需要手动配置Fluent验证,以便可以将模型错误添加到ModalState? 解决方法
正如
documentation所解释的那样,请确保在Application_Start中添加以下行以交换数据注释模型元数据提供程序并使用流畅验证:
FluentValidationModelValidatorProvider.Configure(); 你的行动中的以下评论也让我害怕: /* This is a method in viewmodel that fills dropdownlists from db */ model.FillDropDownLists(); View模型不应该知道数据库的含义.因此在视图模型中使用这样的方法是一种非常错误的方法. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- .NET Core的日志[2]:将日志输出到控制台
- asp.net-mvc – asp mvc使用View Model在视图中列出产品详细
- regex – RegularExpressionAttribute – 如何使它不区分大
- asp.net-mvc-3 – 如何在NHibernate 3.2中实现通用存储库模
- asp.net – 如何使用横向方向将页面大小设置为信封大小?
- asp.net – 如何使用foreach循环清除所有文本框?
- 从ASP.Net WebSite转换为Web应用程序项目后的MasterType问题
- asp-classic – 如何将字符串转换为日期时间格式的经典asp
- asp.net-mvc – 到Spark还是不Spark?
- asp.net-mvc – 在MVC Action中将SSRS报告导出为PDF
推荐文章
站长推荐
- asp.net – 添加到Response.Cookies的Cookie也被
- asp.net-mvc – 如何阻止URL.Action包含参数?
- asp.net – 在WebForms中调试时关闭捆绑/缩小
- asp.net – 在类库中引用RoleProvider
- asp.net-mvc – 将id类型从string更改为int时,如
- asp.net – 所有PartialView的自定义ActionResul
- asp.net-mvc – 将数据动态绑定到asp.net mvc中的
- asp.net-mvc-3 – MVC3 EditorFor动态属性(或需要
- asp.net – 将经典的asp页面映射到IIS中的.net
- asp.net-mvc – ASP.NET MVC:通过所有ActionLin
热点阅读