不管是通过action参数获取一个model,或者是手工calling UpdateModel()还是TryUpdateModel(),默认的DefaultModelBinder都将自动执行合法验证。但是,你用其他的方法更新model时,自动验证则会跳过。例如:

public ActionResult MakeBooking(string clientName, DateTime? appointmentDate,

                                bool acceptsTerms)

{

    var appt = new Appointment {

        ClientName = clientName,

        AppointmentDate = appointmentDate.GetValueOrDefault()

    };

    if (!acceptsTerms)

        ModelState.AddModelError("acceptsTerms", "You must accept the terms");

    if (ModelState.IsValid) {

        // To do: Actually save the appointment to the database or whatever

//绕过验证

        return View("Completed", appt);

    }

    else

        return View(); // Re-renders the same view so the user can fix the errors

}

Controller基类提供了两个基本方法让我们手工触发验证

•  ValidateModel() 验证,如果不合法,将登记错误,并抛出 InvalidOperationException异常

.

•  TryValidateModel()  相对ValidateModel区别在于不抛出异常,只是返回和ModeState.IsValide一样的值。

不管是通过action参数获取一个model,或者是手工calling UpdateModel()还是TryUpdateModel(),默认的DefaultModelBinder都将自动执行合法验证。但是,你用其他的方法更新model时,自动验证则会跳过。例如:

public ActionResult MakeBooking(string clientName, DateTime? appointmentDate,

                                bool acceptsTerms)

{

    var appt = new Appointment {

        ClientName = clientName,

        AppointmentDate = appointmentDate.GetValueOrDefault()

    };

    if (!acceptsTerms)

        ModelState.AddModelError("acceptsTerms", "You must accept the terms");

    if (ModelState.IsValid) {

        // To do: Actually save the appointment to the database or whatever

//绕过验证

        return View("Completed", appt);

    }

    else

        return View(); // Re-renders the same view so the user can fix the errors

}

Controller基类提供了两个基本方法让我们手工触发验证

•  ValidateModel() 验证,如果不合法,将登记错误,并抛出 InvalidOperationException异常

.

•  TryValidateModel()  相对ValidateModel区别在于不抛出异常,只是返回和ModeState.IsValide一样的值。

相关文章:

  • 2022-12-23
  • 2021-11-17
  • 2021-12-09
  • 2022-12-23
  • 2022-02-20
  • 2021-07-28
  • 2022-12-23
  • 2021-12-03
猜你喜欢
  • 2021-08-14
  • 2021-10-25
  • 2022-01-18
  • 2021-07-24
  • 2021-09-23
  • 2021-07-28
  • 2021-12-09
相关资源
相似解决方案