@RenderPartial()
將分布視圖直接寫入響應輸出流,所以只能直接放在代碼塊中,不能放在表達式中(返回值是void)
RenderPartial 不需要創建 Controller 的 Action ,而 RenderAction 需要在 Controller 創建要加載的 Action。RenderAction 會先去調用 Contorller 的 Action ,最后再 呈現視圖,所以這里 頁面會在 發起一個鏈接。如果這個部分視圖只是一些簡單 的 html 代碼,請使用 RenderPartial。 但如果這個部分視圖 除了有 html 代碼外,還需要 通過 讀取數據庫里的數據 來渲染,就必須使用 RenderAction 了,因為 它可以在 Action 里調用 Model里的 法讀取數據庫,渲染視圖后在呈現,而 RenderPartial 沒有 Action,所以無法做到。
Partial 可以直接輸出內容,它內部是 將 html 內容轉換為 string 字符(MVCHtmlString),然后緩存起來, 最后在一次性輸出到頁面。顯然,這個轉換的過程,會降低效率,所以通常使用 RenderPartial 代替。
(廢話少說,上代碼)
案例一:在主視圖A 調用控制器B呈現部分視圖B
這是部分視圖B的控制器代碼:
[ChildActionOnly] public PartialViewResult ChildAction(DateTime time) { string greetings = string.Empty; if (time.Hour > 18) { greetings = "Good evening. Now is " + time.ToString("HH:mm:ss"); } else if (time.Hour > 12) { greetings = "Good afternoon. Now is " + time.ToString("HH:mm:ss"); } else { greetings = "Good morning. Now is " + time.ToString("HH:mm:ss"); } return PartialView("ChildAction", greetings); }
這是分部視圖B的視圖代碼:
@model string
<h2>@Model</h2>
<h2>這是分部視圖B</h2>
這是主視圖A的控制器代碼,不需要寫什么,返回主視圖A就行:
// GET: Hom public ActionResult Index() { return View(); }
這是主視圖A的視圖代碼:
@{ Layout = null; } <h2>主頁前</h2>
//鏈接到分部視圖B的控制器 @Html.Action("ChildAction", new { time = DateTime.Now }) <h2>主頁后</h2>
運行效果:
在案例一基礎上實現無刷新分部視圖效果:
要通過ajax來調用ChildAction返回PartialView,首先要去掉ChildAction開頭寫的[ChildActionOnly]。因為這種調用方法不算ChildAction調用。
再將主視圖A的代碼修改為:
@{ Layout = null; } <script src="~/Scripts/jquery-1.10.2.js"></script> <h2>主頁前</h2> <hr /> <div id="header"></div> <hr /> <h2>主頁后</h2> <script>
//設置為每1秒在主視圖A更新部分視圖B一次 setInterval(LoadAction, 1000); function LoadAction() { var time = new Date(); $.ajax({ type: "POST", url: '@Url.Action("ChildAction", "Hom")', data: { time: time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds()}, datatype: "json", success: function (data) { $('#header').html(data); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert(errorThrown); } }); } </script>
其他代碼不需要改變。
即可實現在主視圖局部刷新分部視圖。
案例二:
Home控制器:
public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult PartialPage(string name, int id) { ViewBag.id = id; ViewBag.name = name; return View("~/Views/Shared/PartialPage.cshtml"); } }
Index視圖:
@Html.Action("PartialPage", "Home", new { name = "SharpL", id = 1 }) <p>原視圖中的p元素</p>
在Views下的Shared下新建部分PartialPage視圖:
<p>我是分部視圖</p> <p>博客名為:@ViewBag.name</p> <p>博客的id為:@ViewBag.id</p>
項目目錄:
運行: