除了DataAnnotationsModelValidationFactory,还有DataErrorInfoModelValidatorProvider。DataErrorInfoModelValidatorProvider提供另一种自定义数据合法性验证支持。Asp.net mvc硬编码支持IDataErrorInfo接口。使用方法为model实现IDataErrorInfo。IDataErrorInfo要求实现返回model级别和属性级别违法信息。

示例:

public class Appointment : IDataErrorInfo

{

    public string ClientName { get; set; }

    public DateTime AppointmentDate { get; set; }

    public string this[string columnName]

    {

        get { 

            if (columnName == "ClientName") {

                if (string.IsNullOrEmpty(ClientName))

                    return "Please enter a name.";

            }

            if (columnName == "AppointmentDate")

            {

                if (AppointmentDate < DateTime.Now.Date)

                    return "Bookings cannot be placed in the past";

            }

            return null; // No property-level errors

        }

    }

    public string Error

    {

        get {

            if (ClientName == "Steve"

                && AppointmentDate.DayOfWeek == DayOfWeek.Saturday)

                return "Steve can't book on Saturdays.";

            return null; // No object-level errors

        }

    }

}

public ActionResult MakeBooking(Appointment appt, bool acceptsTerms)

{

    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

}

相关文章:

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