我有此验证规则来比较两个日期:
public class EmployeeAbsenceValidator : AbstractValidator<EmployeeAbsence>
{
public EmployeeAbsenceValidator() {
RuleFor(a => a.DateTo)
.GreaterThanOrEqualTo(a => a.DateFrom);
}
}
这是用于验证新创建的缺勤时间的控制器代码:
if (ModelState.IsValid)
{
EmployeeAbsenceValidator validator = new EmployeeAbsenceValidator();
ValidationResult result = validator.Validate(employeeAbsence);
if (!result.IsValid)
{
return RedirectToAction("Create", "EmployeeAbsences");
}
else
{
_context.Add(employeeAbsence);
await _context.SaveChangesAsync();
return RedirectToAction("Details", "Employees");
}
}
如果日期无效,我想返回所有表单数据完整的表单。我该怎么办?
答案 0 :(得分:2)
假设您的GET
和POST
操作方法的操作名称相同,然后使用return this.View( model )
,如下所示:
if (ModelState.IsValid)
{
EmployeeAbsenceValidator validator = new EmployeeAbsenceValidator();
ValidationResult result = validator.Validate(employeeAbsence);
if (!result.IsValid)
{
return this.View( employeeAbsence );
}
else
{
_context.Add(employeeAbsence);
await _context.SaveChangesAsync();
return RedirectToAction("Details", "Employees");
}
}
这会将页面的HTML返回到POST
帮助器(或@Html.ValidationMessageFor( m => m.Foo
帮助器)中的验证错误消息,并返回到<span asp-validator-for="Foo">
请求。