zoukankan      html  css  js  c++  java
  • MVC 验证和异常处理 分开处理Model级别和属性级别验证

     Model和属性级别区分的概念需要参考这种场景:几个属性合一块来决定出一现合法信息属于model级,属性级则在纠缠在本身,比如int型必须是int型这种。

      带来级别的概念是为了解释一种验证信息不好指定为某个属性上时的处理方案。View有两种显示异常的情况一种是summer(Html.ValidationSummary()),一种是each(Html.ValidationMessageFor())。属性界别用each一一对应,模块界别用summer。ModelState.AddModelError也支持key为空,key为空,则信息属于model级别。但是summer默认会显示已经包括在each中所有验证信息,这样会出现重复显示。不过这么使用就可以解决问题:Html.ValidationSummary(true),指定为true只显示model级别的信息,同时,添加key为空的信息。示例:

    public ActionResult MakeBooking(Appointment appt, bool acceptsTerms) {

        if (string.IsNullOrEmpty(appt.ClientName))

            ModelState.AddModelError("ClientName", "Please enter your name");

        if (ModelState.IsValidField("AppointmentDate"))

        {

            // Parsed the DateTime value. But is it acceptable under our app's rules?

            if (appt.AppointmentDate < DateTime.Now.Date)

                ModelState.AddModelError("AppointmentDate", "The date has passed");

            else if ((appt.AppointmentDate - DateTime.Now).TotalDays > 7)

                ModelState.AddModelError("AppointmentDate",

                                         "You can't book more than a week in advance");

        }

        if (!acceptsTerms)

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

        bool isSaturday = appt.AppointmentDate.DayOfWeek == DayOfWeek.Saturday;

        if (appt.ClientName == "Steve" && isSaturday)

           ModelState.AddModelError("" /* key */, "Steve can't book on Saturdays");

        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

    结果:

     

  • 相关阅读:
    论信息系统项目沟通管理
    程序员到底怎么了
    Spring DBCP用xml和properties2种格式配置DataSource
    Spring Aop的理解和简单实现
    数据库常见面试题总结
    java常见面试题总结
    【JavaEE】企业面试问题-Java基础
    Java String常见面试题汇总
    JavaScript事件详解
    JavaScript函数使用技巧
  • 原文地址:https://www.cnblogs.com/wusong/p/1971158.html
Copyright © 2011-2022 走看看