日期:2014-05-16  浏览次数:21322 次

Asp.Net MVC4 系列--进阶篇之Model(2)

在上一章介绍了MVC中model binding,本章将介绍一下MVCmodel validation

和前几章一样,从一个例子开始

准备工作

 

准备model

   public classAppointment
    {
        public string ClientName { get; set; }
       [DataType(DataType.Date)]
        public DateTime Date { get; set; }
        public bool TermsAccepted { get; set; }
}


代码说明:一个预约model,包含了客户姓名,预约日期,以及是否accept合约

 

准备controller

    

public class AppintmentController : Controller
    {
 
        public ViewResult MakeBooking()
        {
            return View("NewAppintment",new  Appointment { Date = DateTime.Now });
        }
 
        [HttpPost]
        public ViewResult MakeBooking(Appointment appt)
        {
            //statements to store new Appointment in a
            //repository would go here in a real project
            return View("Completed", appt);
        }
 
}

代码说明:很经典的”Get-Post-action” 结构,同名方法两个,Get版本用于服务第一次来到页面的请求,post版本用于处理提交页面的请求。

Get版本:render预约页面,获取预约信息

Post版本:获得预约的信息,透传(为了演示)给CompletedView表示预约成功

 

 

准备View

a.      (NewAppintment.cshtml)

@model MVCModelValidation.Models.Appointment
@{
ViewBag.Title = "Make A Booking";
}
<h4>Book an Appointment</h4>
@using (Html.BeginForm()) {
<p>Your name: @Html.EditorFor(m =>m.ClientName)</p>
<p>Appointment Date:@Html.EditorFor(m => m.Date)</p>
<p>@Html.EditorFor(m =>m.TermsAccepted) I accept the terms & conditions</p>
<input  type="submit" value="Make Booking" />
}


代码说明:预约View

 

b.     Completed

@model MVCModelValidation.Models.Appointment
@{
ViewBag.Title = "Completed";
}
<h4>Your appointment is confirmed</h4>
<p>Your name is:<b>@Html.DisplayFor(m => m.ClientName)</b></p>
<p>The date of your appointment is:<b>@Html.DisplayFor(m => m.Date)</b></p>


 

代码说明:预约成功 View

 

 

运行


Make booking


 

可以看到,代码有几个需要验证的地方:

1.      客户姓名必填

2.      预约日期必填

3.      必须accept 合约

 

 

显式验证

由于我们的验证是针对用户提交表单的scenario,因此修改post版本的action就好了:

带validation的action:


[HttpPost]
        public ViewResult MakeBooking(Appointment appt)
        {
            if(string.IsNullOrEmpty(appt.ClientName))
            {
               ModelState.AddModelError("ClientName", "Please enter yourname");
            }
            if(ModelState.IsValidField("Date") && DateTime.Now >appt.Date)
            {
               ModelState.AddModelError("Date", "Please enter a date inthe future");
            }
            if (!appt.TermsAccepted)
            {
               ModelState.AddModelError("TermsAccepted", "You mustaccept the terms");
            }
           if (ModelState.IsValid)
            {