天天看點

ASP.NET MVC實踐系列3-伺服器端資料驗證

我們這裡主要講解ASP.NET MVC中伺服器端得資料驗證,至于用戶端驗證我們會在以後的系列中講到。

在Controller中有一個ModelState屬性,這是一個類型為ModelStateDictionary的ModelState類型的字典集合。在進行資料驗證的時候這個屬性是比較有用的。在使用Html.ValidationMessage()的時候,就是從ModelState中檢測是否有指定的KEY,如果存在,就提示錯誤資訊。

1、基本執行個體

在View中添加如下檔案

<a></a>

ASP.NET MVC實踐系列3-伺服器端資料驗證

Code

&lt;%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %&gt;

    &lt;% using (Html.BeginForm()) {%&gt;

        &lt;fieldset&gt;

            &lt;legend&gt;Fields&lt;/legend&gt;

            &lt;p&gt;

                &lt;label for="id"&gt;id:&lt;/label&gt;

                &lt;%= Html.TextBox("id", Model.id) %&gt;

                &lt;%= Html.ValidationMessage("id", "*") %&gt;

            &lt;/p&gt;

                &lt;label for="Title"&gt;Title:&lt;/label&gt;

                &lt;%= Html.TextBox("Title", Model.Title) %&gt;

                &lt;%= Html.ValidationMessage("Title", "*") %&gt;

             &lt;p&gt;

                &lt;input type="submit" value="Save" /&gt;

        &lt;/fieldset&gt;

    &lt;% } %&gt;

在相應的Controller中添加如下代碼

ASP.NET MVC實踐系列3-伺服器端資料驗證

public ActionResult NewsEdit(int id)

        {

            NewsDataDataContext dc = new NewsDataDataContext();

            return View(dc.News.First(n =&gt; n.id == id));

        }

        [AcceptVerbs(HttpVerbs.Post)]

        public ActionResult NewsEdit(int id, FormCollection formValues)

            News news = new News();

            UpdateModel(news);

            if (String.IsNullOrEmpty(news.Title))

            {

                ModelState.AddModelError("Title", "Title不能為空");

            }

            else

                //進行更新

            return View(news);

View中使用Html.ValidationMessage(string modelName)來對指定的屬性進行驗證:這裡仍然使用的是mvc中預設的約定,modelName的内容如果和ModelState中的key值一樣是就顯示。

其中ValidationSummary()是用于顯示全部的驗證資訊的。跟ASP.NET裡面的ValidationSummary驗證控件差不多。

運作程式得到的結果為:

Html.ValidationMessage()方法會為出錯的屬性的輸入框添加一個名為"input-validation-error"的CSS類,同時後面的提示資訊的CSS類名為"field-validation-error":

ASP.NET MVC實踐系列3-伺服器端資料驗證

 &lt;input class="input-validation-error" id="Title" name="Title" type="text" value="" /&gt;

                &lt;span class="field-validation-error"&gt;*&lt;/span&gt;

CSS類的樣式是可以由我們自己自由定義的

2、應用

這裡我們為之前的News執行個體添加伺服器端驗證,首先我們需要一個傳遞錯誤資訊的類

ASP.NET MVC實踐系列3-伺服器端資料驗證

 public class RuleViolation

    {

        public string ErrorMessage { get; private set; }

        public string PropertyName { get; private set; }

        public RuleViolation(string errorMessage)

            ErrorMessage = errorMessage;

        public RuleViolation(string errorMessage, string propertyName)

            PropertyName = propertyName;

    }

然後為dbml中的News類添加一個partial類,來用于驗證屬性

ASP.NET MVC實踐系列3-伺服器端資料驗證

public partial class News

        public bool IsValid

            get { return (GetRuleViolations().Count() == 0); }

        partial void OnValidate(ChangeAction action)

            if (!IsValid)

                throw new ApplicationException("Rule violations prevent saving");

        public IEnumerable&lt;RuleViolation&gt; GetRuleViolations()

            if (String.IsNullOrEmpty(Title))

                yield return new RuleViolation("必須要輸入标題", "Title");

            if (String.IsNullOrEmpty(Author))

                yield return new RuleViolation("必須要輸入作者", "Author");

            yield break;

Controller中填入如下代碼

ASP.NET MVC實踐系列3-伺服器端資料驗證

[AcceptVerbs(HttpVerbs.Post)]

            News news = dc.News.First(n =&gt; n.id == id);

            try

                UpdateModel(news);

                dc.SubmitChanges();

                return RedirectToAction("Details", new { id = id });

            catch (Exception)

                foreach (var issue in news.GetRuleViolations())

                {

                    ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);

                }

                return View(news);

注:當對DataDataContext執行SubmitChanges方法時會觸發OnValidate分布方法。

4、參考:

<a href="http://www.cnblogs.com/QLeelulu/archive/2008/10/08/1305962.html">http://www.cnblogs.com/QLeelulu/archive/2008/10/08/1305962.html</a>

《Professional ASP.NET MVC 1.0》

本文轉自 你聽海是不是在笑 部落格園部落格,原文連結:http://www.cnblogs.com/nuaalfm/archive/2009/10/27/1590532.html  ,如需轉載請自行聯系原作者

繼續閱讀