愛上MVC3系列~分(fen)部視圖中(zhong)的POST
在PartialView中(zhong)進行表單(dan)提(ti)交,有什么用呢,我來總結一下(xia):
1 這(zhe)個(ge)表單(dan)不只一個(ge)地方用到
2 可能涉及到異步的提(ti)交(jiao)問題
這兩種情況都有可能需要把表單建立在“分部視圖”中,我們為第二種情況為例來說一下用法
首先(xian),我(wo)們有一個用戶登陸的(de)(de)表(biao)單UserLogOn.cshtml,它(ta)在首頁及產品列表(biao)頁可(ke)能都提(ti)供了(le)表(biao)現的(de)(de)情況,而(er)(er)這(zhe)時,我(wo)們為了(le)不(bu)違背DRY原則,所以會把相同(tong)的(de)(de)代(dai)碼提(ti)取出來(lai)放到(dao)一個partial view中(zhong),這(zhe)就是我(wo)們的(de)(de)UserLogOn.cshtml,而(er)(er)它(ta)里面只有視圖的(de)(de)表(biao)現,沒有任何(he)提(ti)交(jiao)的(de)(de)動(dong)作,因為它(ta)可(ke)能被(bei)提(ti)交(jiao)到(dao)不(bu)同(tong)的(de)(de)Action中(zhong)去。
實例選自(zi)大家都熟(shu)悉的MVC自(zi)帶的項目
UserLogOn.cshtml代碼如下:
1 @Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.") 2 3 @using (Html.BeginForm()) { 4 <div> 5 <fieldset> 6 <legend>Account Information</legend> 7 8 <div class="editor-label"> 9 @Html.LabelFor(m => m.UserName) 10 </div> 11 <div class="editor-field"> 12 @Html.TextBoxFor(m => m.UserName) 13 @Html.ValidationMessageFor(m => m.UserName) 14 </div> 15 16 <div class="editor-label"> 17 @Html.LabelFor(m => m.Password) 18 </div> 19 <div class="editor-field"> 20 @Html.PasswordFor(m => m.Password) 21 @Html.ValidationMessageFor(m => m.Password) 22 </div> 23 24 <div class="editor-label"> 25 @Html.CheckBoxFor(m => m.RememberMe) 26 @Html.LabelFor(m => m.RememberMe) 27 </div> 28 29 <p> 30 <input type="submit" value="Log On" /> 31 </p> 32 </fieldset> 33 </div> 34 }
Index.cshtml中(zhong)去調(diao)用(yong)它:
@Html.Partial("UserLogOn")
在HomeController中(zhong)的Index方法(Action)中(zhong)的代碼可能是這樣(yang):
[HttpPost]
public ActionResult Index(LogOnModel model) { if (ModelState.IsValid) { if (MembershipService.ValidateUser(model.UserName, model.Password)) { FormsService.SignIn(model.UserName, model.RememberMe); if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } } else { ModelState.AddModelError("", "The user name or password provided is incorrect."); } } return View(); }
OK,事(shi)實上(shang),在(zai)其他頁面有可(ke)能(neng)(neng)也用到了UserLogOn這(zhe)個(ge)視圖,但它的POST提交可(ke)能(neng)(neng)是不同的,可(ke)能(neng)(neng)同時要做其它的事(shi)件,這(zhe)時,我們(men)就可(ke)以通過@Html.Partial把視力的內容顯(xian)示出(chu)來(lai),而后
來提交事件(jian)在哪一個Action里去寫(xie),這樣可以很好的實現業務的分離。
小知識:
在MVC2.0中,老趙曾經提(ti)出(chu)過將(jiang)SCPX分部視力的(de)內容以字符的(de)形式輸(shu)出(chu),而(er)不是直(zhi)接到(dao)頁面的(de)輸(shu)出(chu)流去相應(ying),而(er)在MVC3.0時代,小(xiao)微(wei)把這(zhe)個功(gong)能進行(xing)了封裝(zhuang)與整合,并提(ti)出(chu)了兩個方法,分別去調(diao)用視圖(tu)和Action:
@Html.Partial()
@Html.Action()
當然,也可以(yi)使用MVC2.0的輸出(chu)流方法:
@{Html.RenderPartial();}
@{Html.RenderAction();}