愛(ai)上MVC3系列~PartialView中的頁面重定向
在(zai)MVC的(de)每個(ge)action中(zhong),都可以指(zhi)定一(yi)種返回頁(ye)面(mian)(mian)的(de)類型,可以是(shi)(shi)ActionResult,這表示返回的(de)頁(ye)面(mian)(mian)為view或者是(shi)(shi)一(yi)個(ge)PartialView,前臺(tai)是(shi)(shi)一(yi)個(ge)全整頁(ye)面(mian)(mian),后臺(tai)是(shi)(shi)頁(ye)面(mian)(mian)的(de)一(yi)部(bu)分。
在以ASPX為(wei)(wei)頁(ye)面引擎(qing)(qing)時,PartialView被(bei)稱為(wei)(wei)分(fen)部視圖,擴展(zhan)(zhan)名為(wei)(wei)ASCX,與webform中(zhong)(zhong)的(de)用戶(hu)控(kong)件(jian)是一(yi)樣的(de),即頁(ye)面中(zhong)(zhong)的(de)一(yi)個(ge)部分(fen);而使(shi)用razor為(wei)(wei)頁(ye)面引擎(qing)(qing)時,PartialView擴展(zhan)(zhan)名還是cshtml,這一(yi)點感覺(jue)與普通(tong)頁(ye)面有些(xie)混亂。不過,這不是今天我要講的(de)重點,今天的(de)重點間在partialview中(zhong)(zhong)進行頁(ye)面重定向(xiang)的(de)方式。
第一種情況:在PartialView中進行表單提示操作后,需要返回別一個PartialView來填充原來的這個PartialView的內容
這種情況需要我們的action返回值類型必須是PartialViewResult,返回代碼必須是PartialView
代碼如下:
1 public PartialViewResult ApplyRegister(User_Register_ApplyModel entity) 2 { 3 User_Register_Apply user_Register_Apply = new User_Register_Apply(); 4 TryUpdateModel(user_Register_Apply); 5 if (ModelState.IsValid) 6 { 7 user_Register_Apply.UserID = VCommons.Utils.GetNewGuid(); 8 VM = user_InfoManager.ApplyRegister(user_Register_Apply); 9 if (!VM.IsComplete) 10 { 11 VM.ToList().ForEach(i => ModelState.AddModelError("", i)); 12 } 13 else 14 return PartialView("ApplySuccess", entity.Email);//返回到指定的PartialView,它將替換ApplyRegister這個視圖內容 15 } 16 return PartialView(); 17 }
第二種情況,在PartialView視圖中提交表單,然后使整個頁面進行一個跳轉,需要注意的是不能用response.redirect,而必須用JS的location.href,前者會在本partial位置進行跳換。
代碼如下:
1 public PartialViewResult UserLogOn(UserLogOnModel entity) 2 { 3 if (ModelState.IsValid) 4 { 5 if (LogOn(new User_Info { Email = entity.Email, Password = entity.Password }).IsComplete) 6 { 7 Response.Write("<script>location.href='home/index';</script>");//在ascx中跳(tiao)到(dao)指定頁,需要(yao)用JS方法(fa) 8 } 9 } 10 return PartialView(); 11 }
第三種情況,也是最簡單的一種情況,在partialview中只是一個鏈接,沒有提交動作,只是將partialview的部分進行重定向,這里代碼使用response.redirect()即可
代碼如下:
1 public PartialViewResult UserLogOn(UserLogOnModel entity) 2 { 3 if (ModelState.IsValid) 4 { 5 if (LogOn(new User_Info { Email = entity.Email, Password = entity.Password }).IsComplete) 6 { 7 Response.Redirect("/home/index"); 8 } 9 } 10 return PartialView(); 11 }
個人建議,對于partialview的action,如果只是返回視圖,而不是返回json和其它格式的對象,最好使用PartialViewResult 進行返回,而不要使用(yong)ActionResult,這樣可(ke)以避免一些不
必要的麻煩。