代碼中已有注釋,不多說。
下面,V層:
@model WebApplication1.Models.GuestResponse Layout = null; !DOCTYPE html html head meta name= viewport content= width=device-width / title RsvpForm /title /head body @using (Html.BeginForm()) @Html.ValidationSummary() p Your name: @Html.TextBoxFor(x = x.Name) /p p Your email: @Html.TextBoxFor(x = x.Email) /p p Your phone: @Html.TextBoxFor(x = x.Phone) /p Will you attend? @Html.DropDownListFor(x = x.WillAttend, new[] { new SelectListItem() {Text = Yes, I ll be there , Value = bool.TrueString}, new SelectListItem() {Text = No, I can t come , Value = bool.FalseString} }, Choose an option ) input type= submit value= Submit RSVP / /body /html
這里注意第一行,
@model WebApplication1.Models.GuestResponse
我們綁定我們寫的數(shù)據(jù)類,這樣我們才能順利創(chuàng)建表單。
然后是C層:
[HttpGet] public ViewResult RsvpForm() { return View(); [HttpPost] public ViewResult RsvpForm(GuestResponse model) if (ModelState.IsValid) // TODO: Email response to the party organizer return View( Thanks , model); else // there is a validation error return View(); }
這里我們有兩個RsvpForm,我們在上面添加提交方式,分別是Get和Post
if (ModelState.IsValid)
是否通過數(shù)據(jù)驗證,通過返回視圖Thanks,且把表單傳過來的值傳給Thanks視圖
數(shù)據(jù)驗證不通過,返回原視圖,
這里注意V層
@Html.ValidationSummary()
添加這句話,在數(shù)據(jù)驗證的時候,數(shù)據(jù)不通過,視圖層才能顯示我們的錯誤提示信息。
運行截圖演示:
我們只輸入了姓名,其他沒有輸入,提示錯誤信息
我們輸入一個正確的:
然后點擊,調(diào)到Thanks視圖,Thanks視圖代碼如下:
@model WebApplication1.Models.GuestResponse Layout = null; !DOCTYPE html html head meta name= viewport content= width=device-width / title Thanks /title /head body h1 Thank you, @Model.Name! /h1 @if (Model.WillAttend == true) @:It s great that you re coming. The drinks are already in the fridge! else @:Sorry to hear that you can t make it, but thanks for letting us know. /body /html
這里注意,我們也要綁定我們寫的模型類:
@Model.Name
我們輸入的姓名
Model.WillAttend == true
我們輸入的值,像傳其他,跟這樣類似。
結(jié)果截圖:
至此,我們的MVC三層合作,數(shù)據(jù)驗證,完成!
本文講解了ASP.NET MVC 三層合作-數(shù)據(jù)驗證,更多相關(guān)內(nèi)容請關(guān)注php 。
相關(guān)推薦:
簡易 PHP+MySQL 分頁類
兩個不用遞歸的樹形數(shù)組構(gòu)造函數(shù)
HTML轉(zhuǎn)Excel,并實現(xiàn)打印,下載功能
以上就是ASP.NET MVC 三層合作-數(shù)據(jù)驗證的詳細內(nèi)容,html教程
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯(lián)系我們修改或刪除,多謝。
新聞熱點
疑難解答
圖片精選