Html.Partial or Html.RenderPartial with MVC3?

2019-04-05 09:05发布

问题:

I am totally confused even after seeing the following explanation.

<div>
  @Html.Partial("_FeaturedProduct")
</div>

Partial views can be rendered inside a Layout Page (or if using MVC 2/3 w/ASPX, the Master Page) as well as regular views.

There are some cases where you might like to step aside and write directly to the HTTP Response stream rather than having a partial view render the results (partials/views use MvcHtmlString/StringWriter). To do so, use the Html.RenderPartial helper.

<div>
  @Html.RenderPartial("_FeaturedProduct")
</div>

Can someone tell me what it means? What cases where I might like to write direct to the HTTP Response etc. What if my partial view contains just one line like this:

<h1>Hello</h1>

Which should I use and why? What would happen if I used the other?

The following confused me even more: "Use Html.RenderPartial for streaming images or other elements that are media-centric or where faster download times are highly important."

回答1:

See the response below.

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.

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