ASP.NET MVC 2中的資料驗證

來源:互聯網
上載者:User

對照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);        }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.