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,
- public void ConfigureServices(
- IServiceCollection services)
- {
- services.AddMvc();
- }
-
- public void Configure(
- IApplicationBuilder app,
- IHostingEnvironment env)
- {
- app.UseMvc(routes =>
- {
- routes.MapRoute(
- name: "default",
- template: "{controller=Home}/{action=Index}/{id?}");
- });
- }
Add a model to display in the view,
- public class EmployeeViewModel
- {
- public int Id { get; set; }
- public string Firstname { get; set; }
- public string Surname { get; set; }
- public AddressViewModel Address { get; set; }
- }
-
- public class AddressViewModel
- {
- public string Line1 { get; set; }
- public string Line2 { get; set; }
- public string Line3 { get; set; }
- }
Add a controller with action method returning ViewResult:
- public IActionResult Index()
- {
- var model = new EmployeeViewModel
- {
- Id = 1,
- Firstname = "James",
- Surname = "Bond",
- Address = new AddressViewModel
- {
- Line1 = "Secret Location",
- Line2 = "London",
- Line3 = "UK"
- }
- };
- return View(model);
- }
Add parent view Index.cshtml,
- @using Fiver.Mvc.PartialViews.Models.Home
- @model EmployeeViewModel
-
- <div style="border: 1px solid black; margin: 5px">
- <strong>Employee Details (parent view)</strong>
-
- <p>Firstname: @Model.Firstname</p>
- <p>Surname: @Model.Surname</p>
-
- @Html.Partial("_Address.cshtml", Model.Address)
- </div>
Add partial view _Address.cshtml,
- @using Fiver.Mvc.PartialViews.Models.Home
- @model AddressViewModel
-
- <div style="border: 1px dashed red; margin: 5px">
- <strong>Address Details (partial view)</strong>
-
- <p>Lin1: @Model.Line1</p>
- <p>Line2: @Model.Line2</p>
- <p>Line3: @Model.Line3</p>
- </div>
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.
Source Code
GitHub