How Html.Partial is different from Html.RenderPartial?

The interviewer asked me this question once in an interview. Both look the same and are used to render the partial view. But there is a difference between these two.

Basic knowledge of the MVC application is required to go ahead with this article.

 Html.Partial: It renders partial view and returns mvcHtmlString. It can be stored in a variable and can be manipulated and render again.

 Here I have created partial view Partial1.html.

 Steps to create a partial view:

 Step1: Right-click on the shared folder inside the view folder.

Step2: Enter the name of partial view Partial1.html.

Step3: Check the “create a partial view” check box.

 

image

 

Add Content of partial view like “<h2>Hello</h2>”

 

Razor View Code:

@{
    ViewBag.Title = "Home Page";
}


@{

 var mvcHtmlString =   @Html.Partial("~/Views/Shared/Partial1.cshtml");

}

@Html.Label(mvcHtmlString.ToString() + "<h2>Hi</h2>");

Html.Partial is returning HTML string in the above code sample. Here I have appended “<h2>hi</h2>” in html string and again displayed in the label. So the output will be like below.

 

image

 

Html.RenderPartial: It renders partial view and returns void.

@{Html.RenderPartial(“~/Views/Shared/Partial1.cshtml”);}

 

Conclusion:

1. Html.Partial returns html string.

2. Html.RenderPartial returns void.

3. Html.RenderPartial is faster than Html.Partial since it does not return string.

 

Please provide your valuable suggestion or comment to improve this article.

Happy CodingSmile

Leave a Comment