Using partial views

So far, we've learned how to create view pages using Razor, but sometimes, we have to repeat elements within all or some of our view pages. Wouldn't it be helpful if we could create reusable components within our views? Unsurprisingly, ASP.NET Core 3 implements this feature by default by providing so-called partial views. 

Partial views are rendered within calling view pages. Like standard view pages, they also have the .cshtml file extension. We can define them once and then use them within all our view pages. What a great way to optimize our code by reducing code duplication, which leads to better quality and less maintenance!


Let's look at how we can benefit from this right now. To do this, we will be optimizing the Layout and Mobile layout pages so that they only use a single menu:

  1. Go to the Views/Shared folder and add a new MVC view page called _Menu.cshtml. It will be used as the menu partial view

  1. Copy the nav bar from one of the layout pages and paste it into the menu partial view: 
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-
controller="Home" asp-action="Index">Home</a>
</li>

<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-
controller="Leaderboard" asp-
action="Index">Leaderboard</a>
</li>

<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-
controller="Home" asp-action="Privacy">Privacy</a>
</li>
</ul>
</div>
  1. Replace nav bar with <partial name="_Menu" /> in both layout pages.
  2. Start the application and validate that everything is still working. You shouldn't see any differences, but that is a good thing; you have encapsulated and centralized the menu in a partial view now.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.242.175