對照scottgu的部落格,我試用了一下這個新增的資料驗證功能,總的來說,還是比較方便的。我簡單地總結步驟如下
1. 添加引用
2. 修改業務實體類,在需要進行驗證的Property上面添加一些特殊的Attribute
using System.ComponentModel.DataAnnotations;namespace Web.Models{ public class GalleryListItem { [Required(ErrorMessage="標題是必須的")] public string Title { get; set; } public string Key { get; set; } public string Photo { get; set; } public string Description { get; set; } }}
3. 在頁面中添加指令碼引用
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script> <script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script> <script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
備忘:這裡必須使用MicrosoftMvcAjax,而不能使用jquery的那個validate.js
MicrosoftMvcAjax貌似會解析Model的所有屬性,然後產生有關的驗證規則,如所示
4. 在頁面中啟用驗證
<% Html.EnableClientValidation(); %>
5. 文字框應該採用類似使用如下的文法綁定
<p> <label for="Title"> 標題:</label> <%= Html.TextBoxFor(m=>m.Title)%> <%= Html.ValidationMessageFor(m=>m.Title)%> </p> <p> <label for="Description"> 描述:</label> <%= Html.TextBoxFor(m=>m.Description)%> <%= Html.ValidationMessageFor(m=>m.Description) %> </p>
6. Action代碼中使用下面代碼進行驗證(因為用戶端可能禁用javascript,所以服務端還是要驗證的)
[AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(Models.GalleryListItem model) { if (ModelState.IsValid) { try {//這裡做一些儲存的操作 return RedirectToAction("List"); } catch { return View(model); } } return View(model); }