首页 > 代码库 > ASP.NET MVC RenderPartial和Partial的区别

ASP.NET MVC RenderPartial和Partial的区别

 

背景:ASP.NET MVC 4.0

@{ Html.RenderPartial(...); }

public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName){     htmlHelper.RenderPartialInternal(partialViewName, htmlHelper.ViewData, null, htmlHelper.ViewContext.Writer,    ViewEngines.Engines);}

上面是@{ Html.RenderPartial("_ArticleTable"); } RederPartial对应的方法声明

(1).此方法内调用 htmlHelper.ViewContext.Writer 进行输出, 通俗的理解, Html.RenderPartial方法是直接绚烂模板, 将结果直接Reponse到浏览器, 所以在视图语法中需要用大括号{}”接住”RenderPartial方法的返回值. 所以又有人就这样说:RenderXXX的方法返回值是void, 在方法内部进行输出;

(2).强调一点, RenderPartial带"计算"功能, 可以直接"拿到"父View中传入的model,即不用单独为RenderPartial传入model

@Html.Partial(....) 

直接就在chmtl模板页中这么用,无需用大括号{}包住

public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName){    return htmlHelper.Partial(partialViewName, null, htmlHelper.ViewData);}public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, object model, ViewDataDictionary viewData){    using (StringWriter writer = new StringWriter(CultureInfo.CurrentCulture))    {        htmlHelper.RenderPartialInternal(partialViewName, viewData, model, writer, ViewEngines.Engines);        return MvcHtmlString.Create(writer.ToString());    }}

 请注意, Partial方法将结果输出到临时变量StringWriter ;

ASP.NET MVC RenderPartial和Partial的区别