ASP.NET MVC ModelState與資料驗證

來源:互聯網
上載者:User

ViewData有一個ModelState的屬性,這是一個類型為ModelStateDictionary的ModelState類型的字典集合。在進行資料驗證的時候這個屬性是比較有用的。在使用Html.ValidationMessage()的時候,就是從ViewData.ModelState中檢測是否有指定的KEY,如果存在,就提示錯誤資訊。例如在前一篇文章ASP.NET MVC 入門7、Hellper與資料的提交與綁定中使用到的UpdateModel方法:

我們在View中使用Html.ValidationMessage(string modelName)來對指定的屬性進行驗證:

Html.ValidationMessage()有幾個重載:

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

我們測試一下/Admin/Setting頁面:

在用UpdateModel方法更新BlogSettings.Instance.PostsPerPage的時候,當我們填寫"10d"的時候,由於PostsPerPage為整型的,所以UpdateModel方法就會出錯,同時會往ViewData.ModelState添加相應的錯誤資訊,從而Html.ValidationMessage()方法就可以從ViewData.ModelState中檢測到錯誤並提示。同時Html.ValidationMessage()方法會為出錯的屬性的輸入框添加一個名為"input-validation-error"的CSS類,同時後面的提示資訊的CSS類名為"field-validation-error":

CSS類的樣式是可以由我們自己自由定義的。如的紅色高亮顯示。

好,下面我們來實現發表新隨筆的功能。我們先寫一個提供使用者輸入隨筆內容的表單頁面:

<p>
<label for="Title">標題</label>
<%=Html.TextBox("Title", new { id = "Title", @class = "required" })%>
<%=Html.ValidationMessage("Title")%>
</p>
<p>
<label for="Content">內容</label>
<%=Html.TextArea("Content")%>
<%=Html.ValidationMessage("Content")%>
</p>
<p>
<label for="Slug">URL地址別名(如果為空白則和標題同名)</label>
<%=Html.TextBox("Slug", new { id = "Slug", @class = "required" })%>
<%=Html.ValidationMessage("Slug")%>
</p>

然後我們對使用者提交過來的資料進行儲存:

[AcceptVerbs("POST"), ActionName("NewPost")]
public ActionResult SaveNewPost(FormCollection form)
{
    Post post = new Post();
try
    {
        UpdateModel(post, new[] { "Title", "Content", "Slug" });
    }
catch
    {
return View(post);
    }
    post.Save();
return ShowMsg(new List<string>() { "發表新隨筆成功" });
}

由於這三個值都是字串類型,所以如果值為空白的話,UpdateModel也是不會出錯的,而我們的Title和Content是不允許為空白的,或者我們想我們的Slug的長度不能超過100,也就是需要有我們自己的商務規則。這時候我們或許會這樣寫:

try
{
    UpdateModel(post, new[] { "Title", "Content", "Slug" });
}
catch
{
return View(post);
}
if (string.IsNullOrEmpty(post.Title))
{
    ViewData.ModelState.AddModelError("Title", post.Title, "標題不可為空");
}
if (string.IsNullOrEmpty(post.Content))
{
    ViewData.ModelState.AddModelError("Content", post.Content, "內容不可為空");
}
if (!ViewData.ModelState.IsValid)
{
return View(post);
}

ViewData.ModelState提供了一個AddModelError的方法,方便我們添加驗證失敗的資訊。我們可以如上代碼這樣進行對象的商務規則驗證,但是一旦商務規則多了,這樣的代碼是非常壯觀的,而且不好控制。那麼我們該怎麼更好的進行商務規則的驗證呢?得意於BlogEngine.Net的良好架構,我們可以很輕鬆的完成這一點。

首先,讓我們修改一下BlogEngine.Core裡面BusinessBase的代碼。我們前面說過,BusinessBase實現了IDataErrorInfo介面,該介面有個索引器,導致ViewData.Eval()方法調用時搜尋索引器的值時返回String.Empty而使ViewData.Eval()認為是找到值了,從而失效。

我們可以將return string.Empty修改為return null。但我們這裡並不需要用到這個介面,所以我們把該介面去掉,並把相應的代碼注釋了。然後我們再暴露一個BrokenRules的屬性,用於返回當前的所有破壞性商務規則(紅框部分代碼為我們添加的):

BusinessBase提供了一個抽象的ValidationRules方法,用於在業務類重寫這個方法往裡面添加驗證規則(具體請看BusinessBase的Validation節)。


#region Validation

private StringDictionary _BrokenRules = new StringDictionary();
/// <summary>
/// 擷取所有的破壞性規則。
/// 在擷取前請用IsValid進行判斷。
/// </summary>
public StringDictionary BrokenRules
{
get
{
return _BrokenRules;
    }
}

/// <summary>
/// Add or remove a broken rule.
/// </summary>
/// <param name="propertyName">The name of the property.</param>
/// <param name="errorMessage">The description of the error</param>
/// <param name="isBroken">True if the validation rule is broken.</param>
protected virtual void AddRule(string propertyName, string errorMessage, bool isBroken)
{
if (isBroken)
{
        _BrokenRules[propertyName] = errorMessage;
    }
else
{
if (_BrokenRules.ContainsKey(propertyName))
{
            _BrokenRules.Remove(propertyName);
        }
    }
}

/// <summary>
/// Reinforces the business rules by adding additional rules to the
/// broken rules collection.
/// </summary>
protected abstract void ValidationRules();

/// <summary>
/// Gets whether the object is valid or not.
/// </summary>
public bool IsValid
{
get
{
        ValidationRules();
return this._BrokenRules.Count == 0;
    }
}

/// /// <summary>
/// If the object has broken business rules, use this property to get access
/// to the different validation messages.
/// </summary>
public virtual string ValidationMessage
{
get
{
if (!IsValid)
{
            StringBuilder sb = new StringBuilder();
foreach (string messages in this._BrokenRules.Values)
{
                sb.AppendLine(messages);
            }

return sb.ToString();
        }

return string.Empty;
    }
}

#endregion

我們在Post類中重寫這個方法來添加驗證規則:

然後我們可以在Controller的Action中很優雅的書寫我們的代碼來進行商務規則的驗證:

[AcceptVerbs("POST"), ActionName("NewPost")]
public ActionResult SaveNewPost(FormCollection form)
{
    Post post = new Post();
try
    {
        UpdateModel(post, new[] { "Title", "Content", "Slug" });
    }
catch
    {
return View(post);
    }
if (!post.IsValid)
    {
foreach (string key in post.BrokenRules.Keys)
        {
            ViewData.ModelState.AddModelError(key, form[key], post.BrokenRules[key]);
        }
return View(post);
    }
    post.Save();
return ShowMsg(new List<string>() { "發表新隨筆成功" });
}

我們注意到上面的Action中用到了一個FormCollection 的參數,這個參數系統會自動將Form提交過來的全部表單值(Request.Form)賦給它的。用戶端驗證可以用jQuery的驗證外掛程式來,這裡就不羅嗦了。

暫時就寫這麼多吧,想到什麼再補充。Enjoy!Post by Q.Lee.lulu。

本文的Blog程式範例程式碼: 4mvcBlog_8.rar

物流,配貨,貨運,網站,論壇,交流,資訊發布
網站建設QQ:471226865

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.