What is the difference (if any) between Html.Partial(view, model) and Html.RenderPartial(view,model) in MVC2?

前端 未结 2 2098
执念已碎
执念已碎 2020-11-28 19:15

Other than the type it returns and the fact that you call it differently of course

<% Html.RenderPartial(...); %>
<%= Html.Partial(...) %>  


        
相关标签:
2条回答
  • 2020-11-28 19:24

    This is a great explanation by Dino Esposito:

    The difference between the two methods may look small and harmless, but it may bite at you if you don’t know how to handle it. The key difference between the two methods is:

    • Partial returns a HTML-encoded string
    • RenderPartial is a void method that writes directly to the response output stream.

    The usage of the two methods is slightly different:

    @Html.Partial("_yourPartialView")
    @{ Html.RenderPartial("_yourPartialView "); }
    

    The choice of which to use depends on your requirements. If you need to further manipulate the string being injected in the response stream, you should use Partial; otherwise go with RenderPartial which is-just because it goes straight to the stream-a little faster than Partial.

    In the end, the use-cases for partial views fall in either of two camps. The first is when you create a view by composing together various independent pieces of markup, as below.

    <body>
        @{ Html.RenderPartial("_Header"); }
        @Html.Partial("_Sidebar")
        <div class="container body-content">
           @RenderBody()
        </div>
        @{ Html.RenderPartial("_Footer"); }
    </body>
    

    In this case, your decision in choosing between RenderPartial or Partial doesn’t change the final effect. However, because RenderPartial is slightly faster, you may prefer using it.

    0 讨论(0)
  • 2020-11-28 19:50

    The only difference is that Partial returns an MvcHtmlString, and must be called inside <%= %>, whereas RenderPartial returnsvoid and renders directly to the view.

    If you look at the source code, you'll see that they both call the same internal method, passing a StringWriter for it to render to.

    You would call Partial if you want to view, save, or manipulate the generated HTML instead of writing it to the page.

    0 讨论(0)
提交回复
热议问题