Asp.Net MVC has got a wonderful feature for reusing view and implementing DRY pattern with Partial View.
What is Partial View?
The Partial View in ASP.NET MVC Application are the views that are rendered within another view (Parent View). The HTML output generated by partial view is rendered into the calling (or parent) view. Like views, partial views use the .cshtml file extension.
How can we use Partial View?
Lets us understand the difference between Html.Partial, Html.RenderPartial, Html.Action and Html.RenderAction and how to implement it.
Html.Partial returns MVCHtmlString which can be assigned to a variable and manipulate if required.
Syntax
@Html.Partial("ViewName")
@{ string htmlData = @Html.Partial("ViewName").ToString(); }
Html.RenderPartial returns void and output will be written directly to the output stream.
Syntax
@{ Html.RenderPartial("ViewName"); }
Note: We can also pass the model to the Partial view using partial and renderpartial.
Syntax
@Html.Partial("ViewName", Model)
@{ Html.RenderPartial("ViewName", Model) }
Html.Action Invokes the specified child action method and returns the result as an HTML string
Syntax
@Html.Action("Action", "Controller", new { param = "value"} )
@{string result = @Html.Action("Action", "Controller", new { param = "value"} ).ToString();}
Html.RenderAction Invokes the specified child action method and renders the result inline in the parent view.
Syntax
@{Html.RenderAction("Action", "Controller", new { param = "value"} ).ToString();}
Note: This RenderAction method is faster than the Action method since its result is directly written to the HTTP response stream.