MVC 验证和异常处理 开篇及简单示例

MVC 验证和异常处理 开篇及简单示例。

  背景: MVC 验证和异常处理参考Pro ASP.NET MVC2 Framerowk Seciond Edition.Pdf,将会有书中示例出现在随笔中,或者由于个人能力问题,和原文有偏差。纯属个人加强记忆的随笔。欢迎指正。

  开始第一篇 注册和 显示不合法验证信息

MVC 用ModelState 存储Model在请求间发生的一系列信息,包括后台数据合法性验证 。让我们用一个例子来说明使用方法:

后台定义个model和一个control

public class Appointment

{

    public string ClientName { get; set; }

    [DataType(DataType.Date)]

    public DateTime AppointmentDate { get; set; }

}

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");

    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

重点在ModelState.AddModelError方法,主意它的参数,一个key,一条错误提示,key和view也就是aspx中的绑定的model属性名称一致。

下面看view怎么显示异常信息

最简单的方法是使用Html.ValidationSummary(),统一在某个地方显示所有异常信息。

<h1>Book an appointment</h1>

<%: Html.ValidationSummary() %>

结果大致如图所示

 MVC 验证和异常处理 开篇及简单示例_第1张图片

或者手工指定:

<% using(Html.BeginForm()) { %>

    <p>

        Your name: <%: Html.EditorFor(x => x.ClientName) %>

        <%: Html.ValidationMessageFor(x => x.ClientName) %>

    </p>

    <p>

        Appointment date: 

        <%: Html.EditorFor(x => x.AppointmentDate)%>

        <%: Html.ValidationMessageFor(x => x.AppointmentDate) %>

    </p>

    <p>

        <%: Html.CheckBox("acceptsTerms") %>

        <label for="acceptsTerms">I accept the Terms of Booking</label>

        <%: Html.ValidationMessage("acceptsTerms") %>

    </p>

    

    <input type="submit" value="Place booking" />

<% } %>

结果

 MVC 验证和异常处理 开篇及简单示例_第2张图片

你可能感兴趣的:(异常处理)