Getting Started with ASP.NET Core and Bootstrap 4

0
14287
16 min read

This article is by Pieter van der Westhuizen, author of the book Bootstrap for ASP.NET MVC – Second edition. As developers, we can find it difficult to create great-looking user interfaces from scratch when using HTML and CSS. This is especially hard when developers have extensive experience developing Windows Forms applications. Microsoft introduced Web Forms to remove the complexities of building websites and to ease the switch from Windows Forms to the Web. This in turn makes it very hard for Web Forms developers, and even harder for Windows Forms developers to switch to ASP.NET MVC. Bootstrap is a set of stylized components, plugins, and a layout grid that takes care of the heavy lifting. Microsoft included Bootstrap in all ASP.NET MVC project templates since 2013.

In this article, we will cover the following topics:

  • Files included in the Bootstrap distribution
  • How to create an empty ASP.NET site and enable MVC and static files
  • Adding the Bootstrap files using Bower
  • Automatically compile the Bootstrap Sass files using Gulp
  • Installing additional icon sets
  • How to create a layout file that references the Bootstrap files

(For more resources related to this topic, see here.)

Files included in the Bootstrap distribution

In order to get acquainted with the files inside the Bootstrap distribution, you need to download its source files. At the time of writing, Bootstrap 4 was still in Alpha, and its source files can be downloaded from http://v4-alpha.getbootstrap.com.


Bootstrap style sheets

Do not be alarmed by the amount of files inside the css folder. This folder contains four .css files and two .map files. We only need to include the bootstrap.css file in our project for the Bootstrap styles to be applied to our pages. The bootstrap.min.css file is simply a minified version of the aforementioned file.

The .map files can be ignored for the project we’ll be creating. These files are used as a type of debug symbol (similar to the .pdb files in Visual Studio), which allows developers to live edit their preprocessor source files.

Bootstrap JavaScript files

The js folder contains two files. All the Bootstrap plugins are contained in the bootstrap.js file. The bootstrap.min.js file is simply a minified version of the aforementioned file. Before including the file in your project, make sure that you have a reference to the jQuery library because all Bootstrap plugins require jQuery.

Bootstrap fonts/icons

Bootstrap 3 uses Glyphicons to display various icons and glyphs in Bootstrap sites. Bootstrap 4 will no longer ship with glyphicons included, but you still have the option to include it manually or to include your own icons. The following two icon sets are good alternatives to Glyphicons:

Bootstrap source files

Before you can get started with Bootstrap, you first need to download the Bootstrap source files. At the time of writing, Bootstrap 4 was at version 4 Alpha 3. You have a few choices when adding Bootstrap to you project. You can download the compiled CSS and JavaScript files or you can use a number of package managers to install the Bootstrap Sass source to your project.

In this article, you’ll be using Bower to add the Bootstrap 4 source files to your project.

For a complete list of Bootstrap 4 Alpha installation sources, visit http://v4-alpha.getbootstrap.com/getting-started/download/

CSS pre-processors

CSS pre-processors process code written in a pre-processed language, such as LESS or Sass, and convert it into standard CSS, which in turn can be interpreted by any standard web browser. CSS pre-processors extend CSS by adding features that allow variables, mixins, and functions.

The benefits of using CSS pre-processors are that they are not bound by any limitations of CSS. CSS pre-processors can give you more functionality and control over your style sheets and allows you to write more maintainable, flexible, and extendable CSS.

CSS pre-processors can also help to reduce the amount of CSS and assist with the management of large and complex style sheets that can become harder to maintain as the size and complexity increases.

In essence, CSS pre-processors such as Less and Sass enables programmatic control over your style sheets.

Bootstrap moved their source files from Less to Sass with version 4.  Less and Sass are very alike in that they share a similar syntax as well as features such as variables, mixins, partials, and nesting, to name but a few.

Less was influenced by Sass, and later on, Sass was influenced by Less when it adopted CSS-like block formatting, which worked very well for Less.

Creating an empty ASP.NET MVC site and adding Bootstrap manually

The default ASP.NET 5 project template in Visual Studio 2015 Update 3 currently adds Bootstrap 3 to the project. In order to use Bootstrap 4 in your ASP.NET project, you’ll need to create an empty ASP.NET project and add the Bootstrap 4 files manually.

To create a project that uses Bootstrap 4, complete the following process:

  1. In Visual Studio 2015, select New | Project from the File menu or use the keyboard shortcut Ctrl + Shift + N.
  2. From the New Project dialog window, select ASP.NET Core Web Application (.NET Core), which you’ll find under Templates | Visual C# | Web. Bootstrap for ASP.NET MVC - Second Edition
  3. Select the Empty project template from the New ASP.NET Core Web Application (.NET Core) Project dialog window and click on OK.Bootstrap for ASP.NET MVC - Second Edition

Enabling MVC and static files

The previous steps will create a blank ASP.NET Core project. Running the project as-is will only show a simple Hello World output in your browser. In order for it to serve static files and enable MVC, we’ll need to complete the following steps:

  1. Double-click on the project.json file inside the Solution Explorer in Visual Studio.
  2. Add the following two lines to the dependencies section, and save the project.json file:
"Microsoft.AspNetCore.Mvc": "1.0.0",

"Microsoft.AspNetCore.StaticFiles": "1.0.0"
  1. You should see a yellow colored notification inside the Visual Studio Solution Explorer with a message stating that it is busy restoring packages.
  2. Open the Startup.cs file. To enable MVC for the project, change the ConfigureServices method to the following:
public void ConfigureServices(IServiceCollection services)

{

    services.AddMvc();

}
  1. Finally, update the Configure method to the following code:
public void Configure(IApplicationBuilder app, IHostingEnvironment env,

ILoggerFactory loggerFactory)

{

    loggerFactory.AddConsole();

 

    if (env.IsDevelopment())

    {

        app.UseDeveloperExceptionPage();

    }

 

    app.UseStaticFiles();

 

    app.UseMvc(routes =>

    {

        routes.MapRoute(

            name: "default",

            template: "{controller=Home}/{action=Index}/{id?}");

    });

}
  1. The preceding code will enable logging and the serving of static files such as images, style sheets, and JavaScript files. It will also set the default MVC route.

Creating the default route controller and view

When creating an empty ASP.NET Core project, no default controller or views will be created by default. In the previous steps, we’ve created a default route to the Index action of the Home controller. In order for this to work, we first need to complete the following steps:

  1. In the Visual Studio Solution Explorer, right-click on the project name and select Add | New Folder from the context menu.
  2. Name the new folder Controllers.
  3. Add another folder called Views.
  4. Right-click on the Controllers folder and select Add | New Item… from the context menu.
  5. Select MVC Controller Class from the Add New Item dialog, located under .NET Core | ASP.NET, and click on Add. The default name when adding a new controller will be HomeController.cs: Bootstrap for ASP.NET MVC - Second Edition
  6. Next, we’ll need to add a subfolder for the HomeController in the Views folder. Right-click on the Views folder and select Add | New Folder from the context menu.
  7. Name the new folder Home.
  8. Right-click on the newly created Home folder and select Add | New Item… from the context menu.
  9. Select the MVC View Page item, located under .NET Core | ASP.NET; from the list, make sure the filename is Index.cshtml and click on the Add button: Bootstrap for ASP.NET MVC - Second Edition
  10. Your project layout should resemble the following in the Visual Studio Solution Explorer: Bootstrap for ASP.NET MVC - Second Edition

Adding the Bootstrap 4 files using Bower

With ASP.NET 5 and Visual Studio 2015, Microsoft provided the ability to use Bower as a client-side package manager. Bower is a package manager for web frameworks and libraries that is already very popular in the web development community.

You can read more about Bower and search the packages it provides by visiting http://bower.io/

Microsoft’s decision to allow the use of Bower and package managers other than NuGet for client-side dependencies is because it already has such a rich ecosystem.

Do not fear! NuGet is not going away. You can still use NuGet to install libraries and components, including Bootstrap 4!

To add the Bootstrap 4 source files to your project, you need to follow these steps:

  1. Right-click on the project name inside Visual Studio’s Solution Explorer and select Add | New Item….
  2. Under .NET Core | Client-side, select the Bower Configuration File item, make sure the filename is bower.json and click on Add, as shown here: Bootstrap for ASP.NET MVC - Second Edition
  3. If not already open, double-click on the bower.json file to open it and add Bootstrap 4 to the dependencies array. The code for the file should look similar to the following:
{

   "name": "asp.net",

   "private": true,

  "dependencies": {

    "bootstrap": "v4.0.0-alpha.3"

  }

}
  1. Save the bower.json file.

Once you’ve saved the bower.json file, Visual Studio will automatically download the dependencies into the wwwroot/lib folder of your project. In the case of Bootstrap 4 it also depends on jQuery and Tether, you’ll notice that jQuery and Tether has also been downloaded as part of the Bootstrap dependency.

After you’ve added Bootstrap to your project, your project layout should look similar to the following screenshot:

Bootstrap for ASP.NET MVC - Second Edition

Compiling the Bootstrap Sass files using Gulp

When adding Bootstrap 4, you’ll notice that the bootstrap folder contains a subfolder called dist. Inside the dist folder, there are ready-to-use Bootstrap CSS and JavaScript files that you can use as-is if you do not want to change any of the default Bootstrap colours or properties.

However, because the source Sass files were also added, this gives you extra flexibility in customizing the look and feel of your web application. For instance, the default colour of the base Bootstrap distribution is gray; if you want to change all the default colours to shades of blue, it would be tedious work to find and replace all references to the colours in the CSS file.

For example, if you open the _variables.scss file, located in wwwroot/lib/bootstrap/scss, you’ll notice the following code:

$gray-dark:                 #373a3c !default;

$gray:                      #55595c !default;

$gray-light:                #818a91 !default;

$gray-lighter:              #eceeef !default;

$gray-lightest:             #f7f7f9 !default;

We’re not going to go into too much detail regarding Sass in this article, but the $ in front of the names in the code above indicates that these are variables used to compile the final CSS file. In essence, changing the values of these variables will change the colors to the new values we’ve specified, when the Sass file is compiled.

To learn more about Sass, head over to http://sass-lang.com/

Adding Gulp npm packages

We’ll need to add the gulp and gulp-sass Node packages to our solution in order to be able to perform actions using Gulp. To accomplish this, you will need to use npm.

npm is the default package manager for the Node.js runtime environment. You can read more about it at https://www.npmjs.com/

To add the gulp and gulp-sass npm packages to your ASP.NET project, complete the following steps:

  1. Right-click on your project name inside the Visual Studio Solution Explorer and select Add | New Item… from the project context menu.
  2. Find the npm Configuration File item, located under .NET Core | Client-side. Keep its name as package.json and click on Add.

Bootstrap for ASP.NET MVC - Second Edition

  1. If not already open, double-click on the newly added package.json file and add the following two dependencies to the devDependencies array inside the file:
"devDependencies": {

  "gulp": "3.9.1",

  "gulp-sass": "2.3.2"

}
  1. This will add version 3.9.1 of the gulp package and version 2.3.2 of the gulp-sass package to your project. At the time of writing, these were the latest versions. Your version numbers might differ.

Enabling Gulp-Sass compilation

Visual Studio does not compile Sass files to CSS by default without installing extensions, but we can enable it using Gulp.

Gulp is a JavaScript toolkit used to stream client-side code through a series of processes when an event is triggered during build. Gulp can be used to automate and simplify development and repetitive tasks, such as the following:

Minify CSS, JavaScript and image files

Rename files

Combine CSS files

Learn more about Gulp at http://gulpjs.com/

Before you can use Gulp to compile your Sass files to CSS, you need to complete the following tasks:

  1. Add a new Gulp Configuration File to your project by right-cing Add | New Item… from the context menu. The location of the item is .NET Core | Client-side.
  2. Keep the filename as gulpfile.js and click on the Add button. Bootstrap for ASP.NET MVC - Second Edition
  3. Change the code inside the gulpfile.js file to the following:
var gulp = require('gulp');

var gulpSass = require('gulp-sass');

gulp.task('compile-sass', function () {

    gulp.src('./wwwroot/lib/bootstrap/scss/bootstrap.scss')

        .pipe(gulpSass())

        .pipe(gulp.dest('./wwwroot/css'));

});

The code in the preceding step first declares that we require the gulp and gulp-sass packages, and then creates a new task called compile-sass that will compile the Sass source file located at /wwwroot/lib/bootstrap/scss/bootstrap.scss and output the result to the /wwwroot/css folder.

Running Gulp tasks

With the gulpfile.js properly configured, you are now ready to run your first Gulp task to compile the Bootstrap Sass to CSS. Accomplish this by completing the following steps:

  1. Right-click on gulpfile.js in the Visual Studio Solution Explorer and choose Task Runner Explorer from the context menu.
  2. You should see all tasks declared in the gulpfile.js listed underneath the Tasks node. If you do not see tasks listed, click on the Refresh button, located on the left-hand side of the Task Runner Explorer window.Bootstrap for ASP.NET MVC - Second Edition
  3. To run the compile-sass task, right-click on it and select Run from the context menu.
  4. Gulp will compile the Bootstrap 4 Sass files and output the CSS to the specified folder.

Binding Gulp tasks to Visual Studio events

Right-clicking on every task in the Task Runner Explorer in order to execute each, could involve a lot of manual steps. Luckily, Visual Studio allows us to bind tasks to the following events inside Visual Studio:

  • Before Build
  • After Build
  • Clean
  • Project Open

If, for example, we would like to compile the Bootstrap 4 Sass files before building our project, simply select Before Build from the Bindings context menu of the Visual Studio Task Runner Explorer:

Bootstrap for ASP.NET MVC - Second Edition

Visual Studio will add the following line of code to the top of gulpfile.js to tell the compiler to run the task before building the project:

/// <binding BeforeBuild='compile-sass' />

Installing Font Awesome

Bootstrap 4 no longer comes bundled with the Glyphicons icon set. However, there are a number of free alternatives available for use with your Bootstrap and other projects. Font Awesome is a very good alternative to Glyphicons that provides you with 650 icons to use and is free for commercial use.

Learn more about Font Awesome by visiting https://fortawesome.github.io/Font-Awesome/

You can add a reference to Font Awesome manually, but since we already have everything set up in our project, the quickest option is to simply install Font Awesome using Bower and compile it to the Bootstrap style sheet using Gulp. To accomplish this, follow these steps:

  1. Open the bower.json file, which is located in your project route. If you do not see the file inside the Visual Studio Solution Explorer, click on the Show All Files button on the Solution Explorer toolbar.
  2. Add font-awesome as a dependency to the file. The complete listing of the bower.json file is as follows:
{

  "name": "asp.net",

  "private": true,

  "dependencies": {

    "bootstrap": "v4.0.0-alpha.3",

    "font-awesome": "4.6.3"

  }

}
  1. Visual Studio will download the Font Awesome source files and add a font-awesome subfolder to the wwwroot/lib/ folder inside your project.
  2. Copy the fonts folder located under wwwroot/font-awesome to the wwwroot folder.
  3. Next, open the bootstrap.scss file located in the wwwroot/lib/bootstrap/scss folder and add the following line at the end of the file:
$fa-font-path: "/fonts";

@import "../../font-awesome/scss/font-awesome.scss";
  1. Run the compile-sass task via the Task Runner Explorer to recompile the Bootstrap Sass.

The preceding steps will include Font Awesome in your Bootstrap CSS file, which in turn will enable you to use it inside your project by including the mark-up demonstrated here:

<i class="fa fa-pied-piper-alt"></i>

Creating a MVC Layout page

The final step for using Bootstrap 4 in your ASP.NET MVC project is to create a Layout page that will contain all the necessary CSS and JavaScript files in order to include Bootstrap components in your pages. To create a Layout page, follow these steps:

  1. Add a new sub folder called Shared to the Views folder.
  2. Add a new MVC View Layout Page to the Shared folder. The item can be found in the .NET Core | Server-side category of the Add New Item dialog.
  3. Name the file _Layout.cshtml and click on the Add button:Bootstrap for ASP.NET MVC - Second Edition
  4. With the current project layout, add the following HTML to the _Layout.cshtml file:
<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <meta http-equiv="x-ua-compatible" content="ie=edge">

    <title>@ViewBag.Title</title>

    <link rel="stylesheet" href="~/css/bootstrap.css" />

</head>

<body>

    @RenderBody()

 

    <script src="~/lib/jquery/dist/jquery.js"></script>

    <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>

</body>

</html>
  1. Finally, add a new MVC View Start Page to the Views folder called _ViewStart.cshtml. The _ViewStart.cshtml file is used to specify common code shared by all views.
  2. Add the following Razor mark-up to the _ViewStart.cshtml file:
@{

    Layout = "_Layout";

}

In the preceding mark-up, a reference to the Bootstrap CSS file that was generated using the Sass source files and Gulp is added to the <head> element of the file. In the <body> tag, the @RenderBody method is invoked using Razor syntax.

Finally, at the bottom of the file, just before the closing </body> tag, a reference to the jQuery library and the Bootstrap JavaScript file is added. Note that jQuery must always be referenced before the Bootstrap JavaScript file.

Content Delivery Networks

You could also reference the jQuery and Bootstrap library from a Content Delivery Network (CDN). This is a good approach to use when adding references to the most widely used JavaScript libraries. This should allow your site to load faster if the user has already visited a site that uses the same library from the same CDN, because the library will be cached in their browser.

In order to reference the Bootstrap and jQuery libraries from a CDN, change the <script> tags to the following:

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js"></script>

There are a number of CDNs available on the Internet; listed here are some of the more popular options:

Learn more about Bootstrap



LEAVE A REPLY

Please enter your comment!
Please enter your name here