aspnet
  1. aspnet-razor-partial-views

Razor Partial Views

Razor Partial Views allow us to break down the complex UIs into small, reusable parts, making code more manageable and readable. A Partial View in Razor is returned by Controller Action and included in Razor views using RenderPartial() method.

Syntax

@{Html.RenderPartial("PartialViewName");}

Example

Let's create a partial view named "_HelloPartial.cshtml" that will simply display a greeting message

@model string

<div class="jumbotron text-center">
    <h1>Hello, @Model</h1>
</div>

Now, let's include the partial view in the main view using RenderPartial() method.

<h1>Welcome to Razor Partial Views Tutorial</h1>
@{ Html.RenderPartial("_HelloPartial", "ASP.NET"); }

In the above example, we included the _HelloPartial view in the main view, and passed a string ASP.NET as a model to _HelloPartial view.

Output

After running the above code, the output will be,

Welcome to Razor Partial Views Tutorial

Hello, ASP.NET

Explanation

In the above syntax, RenderPartial() method is used to include a partial view in the main view. The method takes two parameters:

  • The name of the partial view (without extension)
  • The model that is to be passed to the partial view

In the example above, we passed the "_HelloPartial" as the name of the partial view and "ASP.NET" as a model to be displayed in _HelloPartial view.

Use

Razor Partial Views are used when we want to have a reusable piece of UI code that can be used in multiple pages. For example, we can create a header, footer, or navigation bar as a partial view and then include them in all pages. Partial Views are also used to break down larger views into smaller, manageable parts.

Important Points

  • The name of the Partial View should be prefixed by an underscore (_).
  • A Partial View should have its own Model or use the same Model as the Main View.
  • HTML rendered from the Partial View is not treated as a separate page because it's merged with the rest of the HTML in the Main View.

Summary

In this tutorial, we learned about Razor Partial Views in ASP.NET. Razor Partial Views allow us to break complex UIs into small, reusable parts making the code more manageable and readable. We've seen how to include a partial view in the main view and passed models to the view.

Published on: