This is the ninth of a new series of posts on ASP .NET Core. In this post, we’ll learn about Razor Class Libraries to build reusable UI for your web app. This post is also included in Matthew Groves‘ 2018 C# Advent Calendar, in the Dec 2 slot.
- 2nd Annual C# Advent: https://crosscuttingconcerns.com/The-Second-Annual-C-Advent
Introduction to Razor Class Libraries
From an earlier post on Pages in ASP .NET Core, we’ve seen various of ways of creating web pages with or without controllers, views and models to support each of your pages. If you’re an experienced developer, you already know how to reuse server-side code in class libraries.
Starting with ASP .NET Core 2.1, you can now “package your Razor views and pages (.cshtml files) along with your controllers, page models, and data models in reusable class libraries that can be packaged and shared. Apps can then include pre-built UI components by referencing these packages and customize the UI by overriding specific views and pages.”
- March 18 announcement: https://blogs.msdn.microsoft.com/webdev/2018/03/01/asp-net-core-2-1-razor-ui-in-class-libraries/
Better yet, ASP .NET Core Identity is now available as a Razor Class Library, and can be scaffolded into your web application with just the pieces you need.
Before You Begin
Before you begin, take a look at the sample code project on GitHub:
GameConsoles on GitHub: https://github.com/shahedc/GameConsoles
Open the GameConsoles.sln file to load the 2 projects included with the solution:
- Web App project (Set as StartUp Project)
- Razor UI Class Library project (contains shared UI for reuse)
Steps to Create in Visual Studio 2017
Create Class Library project, add reusable UI:
- Click File | New | Project
- Select ASP .NET Core Web Application, click OK
- Select Razor Class Library under ASP .NET Core 2.1
Add partial views under /Pages/Shared/
- /Pages/Shared/_Header.cshtml
- /Pages/Shared/_Footer.cshtml
- Create folder structure /Pages/Shared/
- Add new Razor View _Header.cshtml to Shared subfolder
- Add new Razor View _Footer.cshtml to Shared subfolder
Reference for adding new folders and views: https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-view?view=aspnetcore-2.1
Contents of _Header.cshtml:
<h3>_Header.cshtml partial view.</h3> <p>/Pages/Shared/_Header.cshtml</p> <a href="/">Home</a>
Contents of _Footer.cshtml:
<h3>_Footer.cshtml partial view.</h3> <p>/Pages/Shared/_Footer.cshtml</p> Source: <a href="https://en.wikipedia.org/wiki/List_of_home_video_game_consoles">https://en.wikipedia.org/wiki/List_of_home_video_game_consoles</a>