(C# ASP.NET Core) Integrating CSS and JS Files with Razor Pages

This is a quick and complete explanation of how to integrate your razor pages to a framework such as bootstrap, and how to add and manage your custom CSS, JS and image files in your application. We explain various files such as the _ViewStart file, the _Layout file, and the special directory wwwroot. The concept is similar to that of master pages in the classic ASP.NET. The article also contains a linked video that you can watch for a clearer understanding of how we have integrated bootstrap to a simplest ASP.NET Core application.

Categories | About |     |  

Parveen,

Fixed and variable parts of a webpage

The fixed parts of a webpage can be written once - in a layout file - similar to a master page of the classic ASP.NET.

The variable parts, i.e., the razor pages that contain the actual content of the page are then substituted into a placeholder in a layout file.

Video Explanation

Please watch the following youtube video:

Quick facts about a Layout File

  1. Layout files are typically named _Layout.cshtml
  2. By convention, layout files are placed in a folder called "Shared" - which can be in the root directory, or in a Pages directory depending on the razor pages that will use it.
  3. They contain markup for the fixed portion of the page - such as some meta tags, links to common CSS and JS files, as well as placeholders for the variable content.
  4. You can have as many layout files as needed - and they can even be switched dynamically - through a program in a viewstart file (explained later on this page).

Following is an example of a simple layout file that can integrate the bootstrap framework


// example _Layout.cshtml file 

<!doctype html>

<html lang="en">

<head>

  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />

  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/...  crossorigin="anonymous" />

  <title>@ViewBag.Title</title>

</head>

<body>

  // variable content substitutes from a razor page 
  // see later below for explanation 
  @RenderBody()

  <!-- Bootstrap JS -->
  <script src="https://cdn.js . . . crossorigin="anonymous"></script>

</body>

</html>

How is a razor page "connected" to a layout file?
(see the linked video)

The procedure is to place a file of exactly the same spellings as "_ViewStart.cshtml" and place it ADJACENT to the razor page, i.e., in the same directory.

The role of _ViewStart.cshtml is to specify the path of your _Layout file. Typically, it contains only one statement as below

// _ViewStart.cshtml file 

// usually, this is the only statement 
// but custom code can be added to switch 
// layout files, or to place any additional  
// restrictions through, say, a redirect 
@{
    Layout = "~/Shared/_Layout.cshtml";
}

How is a razor page "substituted" into a layout file?
(see the linked video)

The entire razor page is fitted into a layout file at the place where @RenderBody() is found (see example _Layout.cshtml file above).

However, a razor page can specify additional, page specific, CSS and JS links by defining sections. For example the razor page below defines two sections - one for additional CSS files, and another for the JS files. You can give any valid identifier names to your sections.

// index.cshtml 

@page

// a section called CustomCSS is defined 
@section CustomCSS{

  <link href="starter-template.css" rel="stylesheet" />

}

// another section CustomJS defined 
@section CustomJS{

  <script src="https://cdn. . . . ></script>

  <script src="https://cdn.jsdelivr. . .></script>

  <script src="Provider/dashboard.js"></script>
}


// -------page content not shown 
<h1>Products</h1>

These sections, CustomJS and CustomCSS, get substituted at @RenderSection as shown below.

// _Layout.cshtml file with option RenderSection  

<!doctype html>

<html lang="en">

<head>

  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />

  // bootstrap CSS 
  <link href="https://c. . . />

  <title>@ViewBag.Title</title>

  // optional section, can be used for  
  // page specific CSS files 
  @await RenderSectionAsync("CustomCSS", required: false)

</head>

<body>

  @RenderBody()

  // optional section, can be used for  
  // page specific JS scripts 
  @await RenderSectionAsync("CustomJS", required: false)

  // bootstrap JS 
  <script . . . ></script>

</body>

</html>

Where to place the static CSS, JS, image files?
(see the linked video)

Static content files like your CSS, JS and images must be placed in a folder of exact name and spellings as "wwwroot". It can contain sub-folders. This wwwroot directory is directly in the root of your website. It is a special folder.

The following links to a CSS file called "starter-template.css", which is placed directly inside the wwwroot directory.


<link href="starter-template.css" rel="stylesheet" />

The following links to an image file called "x.png", which is placed directly inside a folder called images under the wwwroot directory.


// BE CAREFUL of the upper-lower case 
// linux is case-sensitive, for example 
<img src="images/x.png" />

Middleware must be configured to connect your app to the wwwroot directory. Do it with a call to UseStaticFiles() as shown thus:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{

  if (env.IsDevelopment())
  {

    app.UseDeveloperExceptionPage();

  }

  // connects your app 
  // to the wwwroot directory 
  app.UseStaticFiles();

  app.UseRouting();

  app.UseEndpoints(endpoints =>
  {

    endpoints.MapRazorPages();

  });

}

Exercises on Layout, CSS Integration and Inter-page linking

for solutions please join our Course on ASP.NET Core with Project ("Find a Doctor")
  1. Create an application with a layout file [full head, body html tags] that shows the current system time in a h1 tag. The file connects to a CSS file called "mycss.css", which is placed in a wwwroot directory, and has a class for a p tag that sets its text color to red. Create a razor page called index that shows your name in a "p" tag. This page should merge into the layout file. Run the app to verify that your name appears in red.
  2. Many CSS frameworks like bootstrap are available on the internet. Find any framework of your choice and create a layout file [full head, body, html, etc.,] by linking its CSS/JS files. Then create two pages - Index and Products. Each page has the same two buttons called "Home" and "Products". When Home is clicked the user should be taken to the Index page, and when Products is clicked the user should be taken to the Products page.

This Blog Post/Article "(C# ASP.NET Core) Integrating CSS and JS Files with Razor Pages" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Comments and Discussion