ASP.NET Core 2.0 MVC Partial Views

Problem

How to reuse parts of web pages using partial views in ASP.NET Core MVC.

Solution

In an empty project update Startup class to add services and middleware for MVC,

Add a model to display in the view,

Add a controller with action method returning ViewResult:

Add parent view Index.cshtml,

Add partial view _Address.cshtml,

Discussion

Partial views are a special type of views that are rendered inside other views. They are useful for reusing parts of a view or splitting a large view into smaller components.

Partial views are created like regular views and can be returned via the controller action method using ViewResult. The key difference is that they don’t run _ViewStart.cshtml before their rendering and are usually rendered inside another view.

Partial views are rendered in views using @Html.Partial() method, passing in the name of partial view and optionally a model. Partial view name can be absolute or relative path and view engine will search the current folder or shared folder.

Partial View gets a copy of parent view’s ViewData dictionary. You could also pass a model into it, which is normally part of parent’s page view model.

Note

ASP.NET Core provides an alternate and more flexible approach to reusing or splitting views that can run code and render views without relying on parent views. Read more about View Components.

Source Code

GitHub

Up Next
    Ebook Download
    View all
    Learn
    View all