zoukankan      html  css  js  c++  java
  • MVC 验证和异常处理 自动验证使用 IDataErrorInfo 接口

    除了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

    }

  • 相关阅读:
    宝宝咳嗽
    如何查看 oracle 官方文档
    00 序 建立环境
    09 变量重游
    【TYVJ】1359
    【COGS】147. [USACO Jan08] 架设电话线(二分+spfa)
    【wikioi】1904 最小路径覆盖问题(最大流+坑人的题+最小路径覆盖)
    【wikioi】1034 家园(最大流+特殊的技巧)
    【BZOJ】1040: [ZJOI2008]骑士(环套树dp)
    【POJ】2234 Matches Game(博弈论)
  • 原文地址:https://www.cnblogs.com/wusong/p/1971183.html
Copyright © 2011-2022 走看看