Loading Custom CSS Files in Razor Pages

Amjad Abujamous - May 23 '20 - - Dev Community

Introduction

Over the past few weeks, I have been working on a Web Application using ASP.NET Core and Razor Pages. The thing that kept frustrating me is how quickly site.css got really big and more difficult to maintain and read. After doing some research online, I found out how to solve that problem. Let's learn how.

Razor Pages Structure

First, it is important to know how Razor Pages figures out how to load your css file. By default, on runtime, The engine reads the file _ViewStart.cshtml to know which layout to load for your page and the link to the default style sheet can be found in it.

This is how the _Layout.cshtml file looks like by default.
Layout_Default

Notice that bootstrap is loaded by default and then the default site.css is loaded. This master page will load these two files to all child pages that use it, such as Views/Home/Index.cshtml.

Project

Say that you are developing an application to help users track their book readings, which page they are currently on in which book, and what books they want to publicly share on their feed.

Your Styles

Now say you want to define custom css to pages that belong to a certain group. For instance, you want specific styles for authentication and user pages and other styles for the rest of the web application.

Essentially, you want the _Layout to dynamically load the css file based on the child page. The trick that will dynamically load a chosen css file into a child page will be done by using the RenderSection feature of ASP.Net Core. That can be done in three simple steps.

Step 1

The first step is to replace loading site.css with @RenderSection("Styles", false). false means that the section is optional in child pages.
Step_1

Step 2

Under wwwroot/css, create user.css and define the styles for user pages in it.
Step_2

Step 3

The third step is to reference this section with the link to your chosen style sheet on your page. For example, on the page Views/User/Register.cshtml we want to load user.css instead of site.css. Be sure to reference site.css in all other default pages in the same way as well.
Step_3

Result

By now, you're done!! Let's give it a little test in which we load two pages and inspect their CSS files. The two pages will be View/Home/Index.cshtml (default) and Views/User/Register.cshtml (loading user.css).
Result

Hope this article helped maintain your styles in an easier manner. Have a good one.

Credit: Cover Photo by RhondaK Native Florida Folk Artist on Unsplash.

. . . . . . . . . . . . . . .