Introduction:

Here we will explain how to use Partial view in MVC or what is Partial view in MVC or how to reduce duplicate coding using Partial view in MVC example.

Description:

Partial view is a special reusable view. It’s like as a user control in asp.net web form application.

Partial view can use multiple in other view. It reduces duplicate coding by reusing same partial view in multiple places.


let's create a simple partial view.


Partial View in Mvc


_MyPartialView.cshtml

 

<h1>This is my Partial View.</h1>
<table style="width:50%">
    <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Age</th>
    </tr>
    <tr>
        <td>Rohan</td>
        <td>Singh</td>
        <td>50</td>
    </tr>
    <tr>
        <td>Brain</td>
        <td>Mark</td>
        <td>94</td>
    </tr>
</table>
<style>  
table, th, td {
   border: 1px solid black;
}
</style>

 

Use Partial View in Index.cshtml

 

@{
    ViewBag.Title = "Index";
}
<h1> using Partial</h1>
@Html.Partial("_MyPartialView")
 
<h1> using RenderPartial</h1>
@{
    Html.RenderPartial("_MyPartialView");
}


when you run above code output will be show like below.


Output:

Partial View in Mvc


  • Html.Partial():

@Html.Partial() helper method renders the partial view as HTML-encoded string. It takes partial view name as a string parameter and returns Html String.

  • Html.RenderPartial():

The RenderPartial helper method is similar to the Partial method except that it returns void and writes resulted html of a given partial view into an http response stream during execution.


I hope it will help to you.

0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

you may also like