Partial Views

In this lesson, we will learn to define reusable Razor markup and to call it from within our views.

Very often the same data is rendered with the same markup. This markup may change with the evolution of the application, but all occurrences are changed so that all occurrences will continue using the same markup.

This is a best practice because using the same UI for the same data decreases the time needed by users to learn the application and improves their speed to execute all operations.

However, we already know that duplication kills modularity and modifiability, so repetitions of markup should be avoided. Instead, we should factor out the repeated markup into a unique place. ASP .NET Core MVC allows us to factor out Razor markup into views that can be called by other views.

Partial views definition

Reusable views are called partial views but they use the same syntax and conventions of standard views, the only difference being that they must not define a layout page since they return HTML fragments. More specifically, views that are called by the views of several controllers should be placed in the Shared folder, while views that are used by the views of a single controller must be placed in that controller folder.

It is best practice to start the file name of each partial view with an underscore, (_), to distinguish them from the usual views.

Partial views can be organized in subfolders so the whole path from the Shared folder or from a specific controller folder must be specified to call them. Thus, for instance, a partial view with a path, Shared/ProductTypes/_Laptop.cshtml must be called with the ProductTypes/_Laptop string.

Calling partial views

Partial views can be called with the two syntaxes shown below:

Get hands-on with 1200+ tech skills courses.