4thSpace
4thSpace

Reputation: 44352

How to add bootstrap to empty asp.net core 2 template app?

In an empty (template) asp.net core 2 app, after adding a Bootstrap package to the project, what else is needed to access Bootstrap?

I can see the Bootstrap NuGet under the NuGet node under dependencies. But none of the Bootstrap files in are wwwroot.

I've added one razor page with a button. However, it displays a normal looking button. Bootstrap isn't being used:

<button type="button" class="btn btn-primary">Primary</button>

Upvotes: 4

Views: 4353

Answers (2)

Brad Patton
Brad Patton

Reputation: 4205

You need to use Bower to install the files (see Manage client-side packages with Bower in ASP.NET Core for more info).

First add bower.json and .bowerrc files to your project root folder.

bower.json contents:

{
  "name": "asp.net",
  "private": true,
  "dependencies": {
    "bootstrap": "3.3.7",
    "jquery": "3.2.1"
  },
  "resolutions": {
    "jquery": "3.2.1"
  }
}

.bowerrc contents

{
  "directory": "wwwroot/lib"
}

Then from the Bower folder under Dependencies you can select Restore Packages and the files will be downloaded.

Bower restore

wwwroot

You can then reference bootstrap in a _Layout.cshtml file with both a relative link for development and a CDN link when published.

<environment include="Development">
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
    <link rel="stylesheet" href="~/css/site.css" />
</environment>
<environment exclude="Development">
    <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
          asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
          asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
    <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
</environment>

And in Startup.cs add UseStaticFiles to enable the web server to return the CSS and JS files.

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider) {
    ...
    app.UseStaticFiles();
    ...
}

Upvotes: 4

pitaridis
pitaridis

Reputation: 2983

The files are not in the js folder. Try the following locations for the files:

<link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>

Upvotes: 0

Related Questions