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

结果:

 

原文地址:https://www.cnblogs.com/wusong/p/1971158.html