Lesson Tuesday

Up to this point, our applications have been pretty plain. In this lesson, we'll cover how to add CSS, images, and JavaScript scripts to our ASP.NET Core MVC web apps.

Structure


When MVC apps run on a server, they use a wwwroot folder as their web root. That means only files in this special folder can be accessed with requests. If we want to include images, CSS, and other content to spruce our pages up, they must also reside in this folder. Otherwise, the GET requests our application uses won't be able to access them.

If we want to add a stylesheet to our project, we need to create a wwwroot directory at the top-level of our ToDoList production project, like this:

ToDoList.Solution
├── ToDoList
│   ├── Controllers
│   ├── Models
│   ├── Program.cs
│   ├── Startup.cs
│   ├── ToDoList.csproj
│   ├── Views
│   └── wwwroot
└── ToDoList.Tests
    ├── ModelTests
    └── ToDoList.Tests.csproj

In that directory, we add a CSS subdirectory with a styles.css file inside it. This folder will store any non-C# related files required to run your application, such as images, videos, music, stylesheets, scripts, etc.

ToDoList.Solution
├── ToDoList
│   ├── Controllers
│   ├── Models
│   ├── Program.cs
│   ├── Startup.cs
│   ├── ToDoList.csproj
│   ├── Views
│   └── wwwroot
│       └── css
│           └── styles.css
└── ToDoList.Tests
    ├── ModelTests
    └── ToDoList.Tests.csproj

Then we link this stylesheet with a standard <link> element on any views that we want to style. To reference the root folder in our <link>, we use the syntax ~/.

For example, our styles.css inside of the ToDoList/wwwroot/CSS folder depicted above could be linked in a view like this:

<link rel="stylesheet" type="text/css" href="~/css/styles.css" />

Adding Static Content


In order to see this in action, let's go over one more example of creating static pages in an MVC app. We're going to make a few new folders so we can display images on our website. In the wwwroot folder, create an img folder. All images will be stored here.

Choose a photo from unsplash.com or elsewhere. Be sure to keep track of photo file names.

Now let’s create a new route in HomeController.cs.

ToDoList/Controllers/HomeController.cs
...

  [Route("/favorite_photos")]
  public ActionResult FavoritePhotos()
  {
    return View();
  }

...

Add a view named FavoritePhotos.

ToDoList/Views/Home/FavoritePhotos.cshtml
  <!DOCTYPE html>
  <html>
    <head>
      <title>My To-Do List!</title>
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    </head>
    <body>
      <h1>Favorite Traveling Photos</h1>
      <ul>
        <li><img src='~/img/photo1.jpg'/></li>
        <li><img src='~/img/photo2.jpg'/></li>
        <li><img src='~/img/photo3.jpg'/></li>
      </ul>
    </body>
  </html>

Unfortunately, if we navigate to http://localhost:5000/favorite_photos, the images aren't showing. This is because our application isn't configured to use static files like images or CSS stylesheets.

Configurations for Using Static Content


Let's update our application configuration to use static content.

Configure the App to Use the Static Files Library: Within our Startup.cs file, we'll add the following to Configure():

Startup.cs
...

  public void Configure(IApplicationBuilder app)
  {
    ...
    app.UseStaticFiles(); //THIS IS NEW
    ...

    app.Run(async (context) =>
    {
      ...
    });    
  }

...

Note that the order of code matters here. app.UseStaticFiles() needs to be before app.Run or the files will not load.

Now we can run $ dotnet build and $ dotnet run to see images on our page.

This image route is not strictly relevant to our To Do List, so it will be removed for the purpose of the example repo. However, as long as your Configure method contains app.UseStaticFiles();, you will be able to add and customize many different types of static content into your projects.

Repository Reference

Follow the link below to view how a sample version of the project should look at this point. Note that this is a link to a specific commit in the repository.

Example GitHub Repo for To Do List

Using Static Content


In order to add CSS or images to our application, we need to update the Startup.cs to UseStaticFiles():

Startup.cs
  public void Configure(IApplicationBuilder app)
  {
    ...
    app.UseStaticFiles(); //THIS IS NEW
    ...

    app.Run(async (context) =>
    {
      ...
    });    
  }

img and css directories need to be inside of wwwroot, which should be in the project's root directory.

└── wwwroot
       └── img
       └── css
           └── styles.css

Now we can link to an image like this:

<img src='~/img/photo1.jpg'/>

Lesson 8 of 11
Last updated more than 3 months ago.