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

后端 未结 13 785
感动是毒
感动是毒 2020-11-22 04:03

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

  • Html.Partial and Html.RenderPartial
  • Html.Action and Html.
13条回答
  •  名媛妹妹
    2020-11-22 04:21

    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);
    }
    

提交回复
热议问题