Introduction to MVC 5 Partial View

Partial View is a special type of view provided by ASP.NET MVC 5 which resides upon the View. In short, we can divide the large view into small parts and can render it using a partial view. The partial view can be reusable in multiple views and helps us to minimize code duplication.

Create a Partial View:

Goto View -> Shared -> Left click on it and Add new View

partial-view-create

It is commonly preferable to start the name of partial view with an underscore(_). This is not compulsory but to distinguish it with other views.

Here we added the partial view as _SideBar.cshtml

<div class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li>@Html.ActionLink("Home", "Index", "Home")</li>
                <li>@Html.ActionLink("About", "About", "Home")</li>
                <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
            </ul>
        </div>
    </div>
</div>

We can Render a partial view using two methods

  • @Html.RenderPartial
  • @Html.Partial

@Html.RenderPartial: RenderPartial method is written directly into the HTTP response method as it uses TextWriter object and it returns nothing.

@Html.Partial: Renders the view as an HTML-encoded string. We can store the method result.

Now render the _SideBar.cshtml in _Layout.cshtml

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

------------------OR--------------------

<div>  
    @{  
        Html.RenderPartial("_SideBar");  
    }  
</div>

We can use any one of above

So Which one is Faster?

The @Html.RenderPartial method writes output directly to the HTTP response stream so it is faster than the @Html.Partial method.

Controller Method for Partial View

public ActionResult DemoPartial()  
{  
    return PartialView();  
}

Now we can also render partial View using jQuery.

<script type="text/jscript">  
        $('#divid').load('/Shared/_SideBar’);  
</script>

You can download this demo from here

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories