模型驗證
一.模型驗證簡介
模型驗證(Model Validation):即確保我們所接收到的數據適合模型綁定,並在不合適時,提醒用戶,以幫助他們修正問題的過程。
準備一個簡單的示例,用來介紹模型驗證。
二.準備一個簡單的示例
新建一個簡單的MVC3空應用程序,並在Models文件夾下新建一個簡單的Person類:
public class Person
{
public string Name { get; set; }
[DataType(DataType.DateTime)]
public DateTime Birthday { get; set; }
public bool HasBrotherOrSister { get; set; }
}
編譯一下項目,在Controller文件夾下新建一個控制器HomeController,修改默認的Index方法,併爲其新建一張基於Person類的強類型視圖: public ActionResult Index(Person person)
{
if (person==null || person.Name == null)
{
person = new Person
{
Name = "Input your name!",
Birthday = DateTime.Parse("1987-2-1"),
HasBrotherOrSister = false
};
}
return View(person);
}
@model ModelValidation.Models.Person
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm())
{
<p>Your Name:@Html.EditorFor(n=>n.Name)</p>
<p>Your BirthDay:@Html.EditorFor(b=>b.Birthday)</p>
<p>@Html.EditorFor(b=>b.HasBrotherOrSister) You have Brother/Sister</p>
<input type="submit" value="Register" />
}
編譯運行,看到如下界面,並修改其值,點擊Register,值隨之變化,證明示例成功進行了模型綁定,準備結束。三.模型驗證方式一
修改Index方法的代碼如下:
public ActionResult Index(Person person)
{
//名字不能爲空
if (string.IsNullOrEmpty(person.Name))
{
ModelState.AddModelError("Name", "Please enter your name!");
}
//生日不能大於當前日期(不符合日期格式的,會自動添加到異常中,這裏無需手動添加)
if (ModelState.IsValidField("Birthday") && DateTime.Now < person.Birthday)
{
ModelState.AddModelError("Birthday", "Please enter a date in the past!");
}
if (ModelState.IsValid)
{
return View(person);
}
else
{
return View();
}
}
修改對應的視圖代碼如下:
@model ModelValidation.Models.Person
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm())
{
@Html.ValidationSummary()
<p>Your Name:@Html.EditorFor(n=>n.Name)</p>
<p>Your BirthDay:@Html.EditorFor(b=>b.Birthday)</p>
<p>@Html.EditorFor(b=>b.HasBrotherOrSister) You have Brother/Sister</p>
<input type="submit" value="Register" />
}
編譯運行,名字不輸入,日期手動填成大於當前日期,檢測效果:以上爲模型驗證的第一種方式。
附:
1.有時候我只想看到某些提示,不想看到所有的提示。如上面的示例,我只想看到第一條提示,卻不想看到第二條提示,怎麼辦呢?
很簡單,這裏介紹一個關鍵詞---“模型級錯誤”,只需將ModelState.AddModelError()首參數變成""即可:
public ActionResult Index(Person person)
{
//名字不能爲空
if (string.IsNullOrEmpty(person.Name))
{
ModelState.AddModelError("", "Please enter your name!"); //注意首參數改成了"",表示模型級錯誤
}
//生日不能大於當前日期(不符合日期格式的,會自動添加到異常中,這裏無需手動添加)
if (ModelState.IsValidField("Birthday") && DateTime.Now < person.Birthday)
{
ModelState.AddModelError("Birthday", "Please enter a date in the past!");
}
if (ModelState.IsValid)
{
return View(person);
}
else
{
return View();
}
}
在修改視圖代碼:@model ModelValidation.Models.Person
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true) //參數true表示只顯示模型級錯誤;否則顯示所有錯誤。
<p>Your Name:@Html.EditorFor(n=>n.Name)</p>
<p>Your BirthDay:@Html.EditorFor(b=>b.Birthday)</p>
<p>@Html.EditorFor(b=>b.HasBrotherOrSister) You have Brother/Sister</p>
<input type="submit" value="Register" />
}
編譯運行,不輸入名字,將生日置成大於當前日期:可見只提示了關於名字的錯誤,卻沒有提示生日大於當前日期的錯誤。
關於ValidationSummary方法,有不少重載,詳見這裏。
2.有時候我不希望錯誤提示顯示在最上面,而是顯示在對應的文本源附近,如何弄呢?
很簡單,修改視圖代碼爲:
@model ModelValidation.Models.Person
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm())
{
<p>Your Name:@Html.EditorFor(n=>n.Name) @Html.ValidationMessageFor(n=>n.Name)</p>
<p>Your BirthDay:@Html.EditorFor(b=>b.Birthday) @Html.ValidationMessageFor(b=>b.Birthday)</p>
<p>@Html.EditorFor(b=>b.HasBrotherOrSister) You have Brother/Sister</p>
<input type="submit" value="Register" />
}
注意不要將錯誤設置成1中的模型級錯誤,否則顯示不出提示!編譯運行,構造輸入錯誤,讓其能夠出提示:
以上,爲模型驗證方式一。