服务器端验证完好且表单数据完好后,如何返回表单?

时间:2018-11-12 09:18:59

标签: c# fluentvalidation asp.net-core-2.1

我有此验证规则来比较两个日期:

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");
    }
}

如果日期无效,我想返回所有表单数据完整的表单。我该怎么办?

1 个答案:

答案 0 :(得分:2)

假设您的GETPOST操作方法的操作名称相同,然后使用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">请求。