在MVC的每個action中,都可以指定一種返回頁面的類型,可以是ActionResult,這表示返回的頁面為view或者是一個PartialView,前台是一個全整頁面,后台是頁面的一部分。
在以ASPX為頁面引擎時,PartialView被稱為分部視圖,擴展名為ASCX,與webform中的用戶控件是一樣的,即頁面中的一個部分;而使用razor為頁面引擎時,PartialView擴展名還是cshtml,這一點感覺與普通頁面有些混亂。不過,這不是今天我要講的重點,今天的重點間在partialview中進行頁面重定向的方式。
第一種情況:在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中跳到指定頁,需要用JS方法 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 進行返回,而不要使用ActionResult,這樣可以避免一些不
必要的麻煩。