Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

In ASP.NET MVC, what is the difference between:

  • Html.Partial and Html.RenderPartial
  • Html.Action and Html.RenderAction

  • Html.Partial returns a String. Html.RenderPartial calls Write internally and returns void .

    The basic usage is:

    // Razor syntax
    @Html.Partial("ViewName")
    @{ Html.RenderPartial("ViewName");  }
    
    // WebView syntax
    <%: Html.Partial("ViewName") %>
    <% Html.RenderPartial("ViewName"); %>
    

    In the snippet above, both calls will yield the same result.

    While one can store the output of Html.Partial in a variable or return it from a method, one cannot do this with Html.RenderPartial . The result will be written to the Response stream during execution/evaluation.

    This also applies to Html.Action and Html.RenderAction .


    Think of @Html.Partial as HTML code copied into the parent page. Think of @Html.RenderPartial as an .ascx user control incorporated into the parent page. An .ascx user control has far more overhead.

    '@Html.Partial' returns a html encoded string that gets constructed inline with the parent. It accesses the parent's model.

    '@Html.RenderPartial' returns the equivalent of a .ascx user control. It gets its own copy of the page's ViewDataDictionary and changes made to the RenderPartial's ViewData do not effect the parent's ViewData.

    Using reflection we find:

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

    差异是第一个返回一个MvcHtmlString但第二个( Render.. )直接输出到响应。

    链接地址: http://www.djcxy.com/p/21190.html

    上一篇: C#中的多行字符串

    下一篇: Html.Partial与Html.RenderPartial&Html.Action与Html.RenderAction