Create Reusable View Using Razor Class Library In ASP.NET Core

In this article, we will discuss the basic concept of Reusable View.

In ASP.NET Core 2.1, a new concept or feature has been introduced by Microsoft, that is called Razor Pages. Razor pages are just like the MVC Razor engine related pages and also, quite similar to the web application pages. Today, in this article, we will discuss the concept and benefits of using Razor pages and also discuss how we can implement the Razor pages in a web application project.
 

WHAT ARE RAZOR PAGES?


One of the most important features in ASP.NET Core is the inclusion of Razor Pages which basically provides us similar flavor of web parts as in previous ASP.NET. So, Razor Pages can be built up with both UI and business logic to develop as a package so that we can reuse that package in any ASP.NET Core application. Obviously, in ASP.NET MVC, there is a concept of Partial Views which can also be used as a reusable UI Component. But the inclusion of business logic within a partial view in the MVC framework is quite difficult to implement. However, in Razor Pages, implementing UI and business logic is much easier and also a more natural fit with the structure of the ASP.NET Core applications.

Actually, ASP.NET Core Razor Pages is a page-oriented framework for developing or building a dynamic, data-driven web application. Razor Pages is much more lightweight and flexible as compared to the previous versions of web parts. This framework is developed on the basis of ASP.NET Core MVC framework so, it can be only activated in the ASP.NET Core application if and only if MVC is enabled in the ASP.NET Core application. The Razor Pages is one of the recommended frameworks for developing cross-platform server-side HTML  in ASP.NET Core.

Razor Pages normally uses the C# programming languages syntaxes for the server-side programming.
 

WHY USE RAZOR PAGES?

 
The main reason to use Razor Pages in ASP.NET Core is that it is a much more organized process. It does not provide us the same facility just like MVC applications. In Razor Pages, we always have a Razor View and a code-behind file just like web forms in the earlier. Razor Pages always works on the Single Responsibility Principle. In simple words, Razor Pages always supports MVVM (Model-View-View-Model) framework. It always provides two-way binding and a simpler development experience with isolated concerns.
 

RAZOR CLASS LIBRARY PROJECT


Razor Class Library (RCL) Projects was first introduced in ASP.NET Core 2.1 for the purpose of packaging and distributions of UI Components which can be referenced and consumed within a host web application. It is basically a library project which contains Razor pages, Razor views, controllers, view components, data models etc. RCL library can be used as a reusable component. It is a very convenient way to share any web parts code with UI elements across the multiple projects. We can also package this in the NuGet Package so that other users can install that package in their own applications and use it.
 

CREATE A RAZOR CLASS LIBRARY FOR RAZOR UI

 
Step 1
 
Open Microsoft Visual Studio 2017 and click on File --> New --> Projects.
 
Create Reusable View Using Razor Class Library In ASP.NET Core
 
Step 2
 
Select Razor Class Library Project Template and click the OK button.
 
Create Reusable View Using Razor Class Library In ASP.NET Core

Step 3
 
First, rename the folder from MyFeature to Library.

Step 4
 
Now, add a Razor Page named _ViewStart.cshtml under the Pages folder and add the below code.
  1. @{  
  2.   
  3.     Layout = "_Layout";  
  4.   
  5. }  
Step 5
 
Now, add a folder called Shared within the Pages folder.

Step 6
 
Now, add a new Razor Page within the Shared folder named _Message.cshtml and add the below code.
  1. <h3>This is a Partial View</h3>  
  2. <p>This Partial view cretead as a Razor Class Library</p>  
Step 7
 
Similarly, add another two Razor pages called _Login.cshtml and _Register.cshtml and then add the below code in the respective files.
 
_Login.cshtml 
  1. <div class="container">  
  2.     <h1>Log in</h1>  
  3.     <div class="row">  
  4.         <div class="col-md-4">  
  5.             <section>  
  6.                 <form id="account" method="post" novalidate="novalidate">  
  7.                     <h4>Use a local account to log in.</h4>  
  8.                     <hr>  
  9.                     <div class="text-danger validation-summary-valid" data-valmsg-summary="true">  
  10.                         <ul>  
  11.                             <li style="display:none"></li>  
  12.                         </ul>  
  13.                     </div>  
  14.                     <div class="form-group">  
  15.                         <label for="Input_Email">Email</label>  
  16.                         <input class="form-control" type="email" data-val="true" data-val-email="The Email field is not a valid e-mail address."   
  17.                                data-val-required="The Email field is required." id="Input_Email" name="Input.Email" value="">  
  18.                         <span class="text-danger field-validation-valid" data-valmsg-for="Input.Email" data-valmsg-replace="true"></span>  
  19.                     </div>  
  20.                     <div class="form-group">  
  21.                         <label for="Input_Password">Password</label>  
  22.                         <input class="form-control" type="password" data-val="true" data-val-required="The Password field is required." id="Input_Password" name="Input.Password">  
  23.                         <span class="text-danger field-validation-valid" data-valmsg-for="Input.Password" data-valmsg-replace="true"></span>  
  24.                     </div>  
  25.                     <div class="form-group">  
  26.                         <div class="checkbox">  
  27.                             <label for="Input_RememberMe">  
  28.                                 <input type="checkbox" data-val="true" data-val-required="The Remember me? field is required." id="Input_RememberMe" name="Input.RememberMe" value="true">  
  29.                                 Remember me?  
  30.                             </label>  
  31.                         </div>  
  32.                     </div>  
  33.                     <div class="form-group">  
  34.                         <button type="submit" class="btn btn-primary">Log in</button>  
  35.                     </div>                      
  36.                 </form>  
  37.             </section>  
  38.         </div>          
  39.     </div>  
  40. </div>  
_Register.cshtml
  1. <div class="container">  
  2.     <h1>Register</h1>  
  3.   
  4.     <div class="row">  
  5.         <div class="col-md-4">  
  6.             <form method="post" action="/Identity/Account/Register" novalidate="novalidate">  
  7.                 <h4>Create a new account.</h4>  
  8.                 <hr>  
  9.                 <div class="text-danger validation-summary-valid" data-valmsg-summary="true">  
  10.                     <ul>  
  11.                         <li style="display:none"></li>  
  12.                     </ul>  
  13.                 </div>  
  14.                 <div class="form-group">  
  15.                     <label for="Input_Email">Email</label>  
  16.                     <input class="form-control" type="email" data-val="true" data-val-email="The Email field is not a valid e-mail address." data-val-required="The Email field is required." id="Input_Email" name="Input.Email" value="">  
  17.                     <span class="text-danger field-validation-valid" data-valmsg-for="Input.Email" data-valmsg-replace="true"></span>  
  18.                 </div>  
  19.                 <div class="form-group">  
  20.                     <label for="Input_Password">Password</label>  
  21.                     <input class="form-control" type="password" data-val="true" data-val-length="The Password must be at least 6 and at max 100 characters long." data-val-length-max="100" data-val-length-min="6"   
  22.                            data-val-required="The Password field is required." id="Input_Password" maxlength="100" name="Input.Password" aria-autocomplete="list">  
  23.                     <span class="text-danger field-validation-valid" data-valmsg-for="Input.Password" data-valmsg-replace="true"></span>  
  24.                 </div>  
  25.                 <div class="form-group">  
  26.                     <label for="Input_ConfirmPassword">Confirm password</label>  
  27.                     <input class="form-control" type="password" data-val="true" data-val-equalto="The password and confirmation password do not match." data-val-equalto-other="*.Password" id="Input_ConfirmPassword"   
  28.                            name="Input.ConfirmPassword">  
  29.                     <span class="text-danger field-validation-valid" data-valmsg-for="Input.ConfirmPassword" data-valmsg-replace="true"></span>  
  30.                 </div>  
  31.                 <button type="submit" class="btn btn-primary">Register</button>  
  32.             </form>  
  33.         </div>  
  34.     </div>  
  35. </div>  
Step 8
 
Now, open the Page1.cshtml file and add the below code.
  1. @page  
  2.   
  3. @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers  
  4.   
  5. <h2>Hello from a Razor UI class library!</h2>  
  6.   
  7. <partial name="_Message" />  
Step 9
 
Now, if we run this page in the browser, then UI components of the _Message.cshtml file will be displayed. 
 
Step 10
 
Now similarly, add two another Razor Pages called Page2.cshtml and Page3.cshtml and the below code.
 
Page2.cshtml 
  1. @page  
  2. @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers  
  3.   
  4. <partial name="_Login" />  
Page3.cshtml
  1. @page  
  2. @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers  
  3.   
  4. <partial name="_Register" />  

USE RAZOR CLASS LIBRARY UI IN WEB APPLICATIONS


Step 1
 
Add other projects in the current solution from File --> Add --> Add Projects.
 
Create Reusable View Using Razor Class Library In ASP.NET Core

Step 2
 
Select Web Application Template and Click on Ok Button

Step 3
 
Now make this project as Startup Projects from Solution Explorer.

Step 4
 
Now, select the Web Application Projects and Right Click and Select Build Dependencies --> Project Dependency.
 
Create Reusable View Using Razor Class Library In ASP.NET Core

Step 5
 
Now select the Razor Class Library projects as a dependency of the current projects

Step 6
 
Now again select the solution explorer and right click and select Add --> Reference.
 
Create Reusable View Using Razor Class Library In ASP.NET Core

Step 7
 
After selecting the Razor Class Library Projects and now click on Ok Button.

Step 8
 
Now open the _Layout.cshtml file and add the below code, 
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0" />  
  6.     <title>@ViewData["Title"] - DemoWebApp</title>  
  7.   
  8.     <environment include="Development">  
  9.         <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />  
  10.     </environment>  
  11.     <environment exclude="Development">  
  12.         <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css"  
  13.               asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"  
  14.               asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute"  
  15.               crossorigin="anonymous"  
  16.               integrity="sha256-eSi1q2PG6J7g7ib17yAaWMcrr5GrtohYChqibrV7PBE="/>  
  17.     </environment>  
  18.     <link rel="stylesheet" href="~/css/site.css" />  
  19. </head>  
  20. <body>  
  21.     <header>  
  22.         <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">  
  23.             <div class="container">  
  24.                 <a class="navbar-brand" asp-area="" asp-page="/Index">DemoWebApp</a>  
  25.                 <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"  
  26.                         aria-expanded="false" aria-label="Toggle navigation">  
  27.                     <span class="navbar-toggler-icon"></span>  
  28.                 </button>  
  29.                 <div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">  
  30.                     <ul class="navbar-nav flex-grow-1">  
  31.                         <li class="nav-item">  
  32.                             <a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>  
  33.                         </li>  
  34.                         <li class="nav-item">  
  35.                             <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>  
  36.                         </li>  
  37.                         <li class="nav-item">  
  38.                             <a asp-page="/Page3" asp-area="Library" class="navbar-brand">Register</a>  
  39.                         </li>  
  40.                     </ul>  
  41.                 </div>  
  42.             </div>  
  43.         </nav>  
  44.     </header>  
  45.     <div class="container">  
  46.         <partial name="_CookieConsentPartial" />  
  47.         <main role="main" class="pb-3">  
  48.             @RenderBody()  
  49.         </main>  
  50.     </div>  
  51.   
  52.     <footer class="border-top footer text-muted">  
  53.         <div class="container">  
  54.             © 2019 - DemoWebApp - <a asp-area="" asp-page="/Privacy">Privacy</a>  
  55.         </div>  
  56.     </footer>  
  57.   
  58.     <environment include="Development">  
  59.         <script src="~/lib/jquery/dist/jquery.js"></script>  
  60.         <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>  
  61.     </environment>  
  62.     <environment exclude="Development">  
  63.         <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"  
  64.                 asp-fallback-src="~/lib/jquery/dist/jquery.min.js"  
  65.                 asp-fallback-test="window.jQuery"  
  66.                 crossorigin="anonymous"  
  67.                 integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=">  
  68.         </script>  
  69.         <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.bundle.min.js"  
  70.                 asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"  
  71.                 asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"  
  72.                 crossorigin="anonymous"  
  73.                 integrity="sha256-E/V4cWE4qvAeO5MOhjtGtqDzPndRO1LBk8lJ/PR7CA4=">  
  74.         </script>  
  75.     </environment>  
  76.     <script src="~/js/site.js" asp-append-version="true"></script>  
  77.   
  78.     @RenderSection("Scripts", required: false)  
  79. </body>  
  80. </html>  
Step 9
 
In the above code, we create a Hyperlink UI Components and link the Register page of the Razor Class Library Projects.

Step 10
 
Now run the applications and the output as below,
Create Reusable View Using Razor Class Library In ASP.NET Core
Step 11
 
Now, add another partial Razor View in the current projects and write down two different anchor links which will redirect to the _Login.cshtml and _Message.cshtml pages, 
  1. <li class="nav-item">  
  2.     <a asp-page="/Page1" asp-area="Library" class="navbar-brand">Page1</a>  
  3. </li>  
  4. <li class="nav-item">  
  5.     <a asp-page="/Page2" asp-area="Library" class="navbar-brand">Login</a>  
  6. </li>  
Step 12
 
Now, place this partial view components in the _Layout.cshtml. 
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0" />  
  6.     <title>@ViewData["Title"] - DemoWebApp</title>  
  7.   
  8.     <environment include="Development">  
  9.         <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />  
  10.     </environment>  
  11.     <environment exclude="Development">  
  12.         <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css"  
  13.               asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"  
  14.               asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute"  
  15.               crossorigin="anonymous"  
  16.               integrity="sha256-eSi1q2PG6J7g7ib17yAaWMcrr5GrtohYChqibrV7PBE="/>  
  17.     </environment>  
  18.     <link rel="stylesheet" href="~/css/site.css" />  
  19. </head>  
  20. <body>  
  21.     <header>  
  22.         <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">  
  23.             <div class="container">  
  24.                 <a class="navbar-brand" asp-area="" asp-page="/Index">DemoWebApp</a>  
  25.                 <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"  
  26.                         aria-expanded="false" aria-label="Toggle navigation">  
  27.                     <span class="navbar-toggler-icon"></span>  
  28.                 </button>  
  29.                 <div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">  
  30.                     <ul class="navbar-nav flex-grow-1">  
  31.                         <li class="nav-item">  
  32.                             <a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>  
  33.                         </li>  
  34.                         <li class="nav-item">  
  35.                             <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>  
  36.                         </li>  
  37.                         <partial name="_EmbeddedView" />  
  38.                         <li class="nav-item">  
  39.                             <a asp-page="/Page3" asp-area="Library" class="navbar-brand">Register</a>  
  40.                         </li>  
  41.                     </ul>  
  42.                 </div>  
  43.             </div>  
  44.         </nav>  
  45.     </header>  
  46.     <div class="container">  
  47.         <partial name="_CookieConsentPartial" />  
  48.         <main role="main" class="pb-3">  
  49.             @RenderBody()  
  50.         </main>  
  51.     </div>  
  52.   
  53.     <footer class="border-top footer text-muted">  
  54.         <div class="container">  
  55.             © 2019 - DemoWebApp - <a asp-area="" asp-page="/Privacy">Privacy</a>  
  56.         </div>  
  57.     </footer>  
  58.   
  59.     <environment include="Development">  
  60.         <script src="~/lib/jquery/dist/jquery.js"></script>  
  61.         <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>  
  62.     </environment>  
  63.     <environment exclude="Development">  
  64.         <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"  
  65.                 asp-fallback-src="~/lib/jquery/dist/jquery.min.js"  
  66.                 asp-fallback-test="window.jQuery"  
  67.                 crossorigin="anonymous"  
  68.                 integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=">  
  69.         </script>  
  70.         <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.bundle.min.js"  
  71.                 asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"  
  72.                 asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"  
  73.                 crossorigin="anonymous"  
  74.                 integrity="sha256-E/V4cWE4qvAeO5MOhjtGtqDzPndRO1LBk8lJ/PR7CA4=">  
  75.         </script>  
  76.     </environment>  
  77.     <script src="~/js/site.js" asp-append-version="true"></script>  
  78.   
  79.     @RenderSection("Scripts", required: false)  
  80. </body>  
  81. </html>  
Step 13
 
Now, run the applications and the output as below -
 
Create Reusable View Using Razor Class Library In ASP.NET CoreCreate Reusable View Using Razor Class Library In ASP.NET Core

CONCLUSION


Now, in this article, we discussed how to implement a partial view or view component using ASP.NET Core. I hope this article will help you understand. In the next article, we will discuss how to Implement Identity Server to authorize any user. For any further query or clarification, ping me.