• 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

    结果:

     

  • 相关阅读:
    ArcGIS Engine开发-三维视图(SceneControl)的刷新
    c#开发基础知识及有用技巧(一)
    ArcGIS Engine开发-取得ArcMap文档缩略图
    RichTextBox中表格不能折行的问题
    Windows WorkFlow Foundation入门(六) 编译工作流
    你还在用 VMware?快试试这款更轻量级的虚拟机!
    RedisJson 横空出世,性能碾压 ES 和 MongoDB!NoSQL 要变天了吗?
    基于 ElasticSearch 实现站内全文搜索,写得太好了!
    团灭!Log4j 1.x 也爆雷了。。。速速弃用!!
    Spring Boot + Redis:抗住 10w 人,秒杀抢单!
  • 原文地址:https://www.cnblogs.com/wusong/p/1971158.html
Copyright © 2020-2023  润新知