我使用FluentValidation MVC5来验证对象。我跟踪了这个教程。当我发布表单时,为什么MVC DefaultModelBinder不验证对象?FluentValidationModelValidatorProvider已在global.asax中配置
Global.asax
protected void Application_Start()
{
FluentValidationModelValidatorProvider.Configure();
}ClientValidationEnabled和UnobtrusiveJavaScriptEnabled在web.config中被设置为真。我还下载了最新的jquery.validation包,添加到BundleConfig,并在它的视图(Create.cshtml)中添加了
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}CurrencyViewModel.cs
[Validator(typeof(CurrencyViewModelValidator))]
public class CurrencyViewModel
{
public int CurrencyID { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
public class CurrencyViewModelValidator : AbstractValidator<CurrencyViewModel>
{
public CurrencyViewModelValidator()
{
RuleFor(x => x.Code).Length(3);
RuleFor(x => x.Name).Length(3, 50);
}
}CurrencyController.cs
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CurrencyViewModel currencyVM)
{
if (ModelState.IsValid)
{
Currency currency = new Currency()
{
Code = currencyVM.Code,
Name = currencyVM.Name
};
db.Currencies.Add(currency);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(currencyVM);
}https://stackoverflow.com/questions/23077470
复制相似问题