How Html.Partial is different from Html.RenderPartial?

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

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

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

 Here I have created partial view Partial1.html.

 Steps to create partial view:

 Step1: Right click on shared folder inside view folder.

Step2: Enter name of partial view Partial1.html.

Step3: Check “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 above code sample. Here I have appended “<h2>hi</h2>” in html string and again displayed in label. So 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

Be the first to comment

Leave a Reply

Your email address will not be published.


*