這個HtmlHelper的擴展方法Partial,和HtmlHelper自帶的 RenderPartial功能比較接近,html
二者均可以輸出一個Partial視圖;其區別以下:ide
<一>. Partial有返回值(MvcHtmlString);RenderPartial沒有返回值(Void)。this
1 //定義 1 //PartialExtensions.Partial 方法 (HtmlHelper, String) 2 public static MvcHtmlString Partial( 3 this HtmlHelper htmlHelper, 4 string partialViewName 5 ) 6 7 //RenderPartialExtensions.RenderPartial 方法 (HtmlHelper, String) 8 public static void RenderPartial( 9 this HtmlHelper htmlHelper, 10 string partialViewName 11 )
<二>不過Partial是將視圖內容直接生成一個字符串並返回,RenderPartial方法是直接輸出至當前 HttpContext。所以它們在視圖中的使用方式是不一樣的,spa
Partial輸出到臨時變量StringWriter ;RenderPartial輸出到HtmlHelper.ViewContext.Writer上(即直接輸出到Response)。
1 Html.Partial內部實現public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName) 2 { 3 return htmlHelper.Partial(partialViewName, null, htmlHelper.ViewData); 4 } 5 6 7 public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, object model, ViewDataDictionary viewData) 8 { 9 using (StringWriter writer = new StringWriter(CultureInfo.CurrentCulture)) 10 { 11 htmlHelper.RenderPartialInternal(partialViewName, viewData, model, writer, ViewEngines.Engines); 12 return MvcHtmlString.Create(writer.ToString()); 13 } 14 } 15 --------------------------------------------------------------------------------- 16 public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName) 17 { 18 htmlHelper.RenderPartialInternal(partialViewName, htmlHelper.ViewData, null, htmlHelper.ViewContext.Writer, ViewEngines.Engines); 19 }
<三>在Razor視圖中語法不同:code
@Html.Partial("PartialViewName") @{ Html.RenderPartial("PartialViewName"); }