Reputation: 2805
I've been assigned to migrate an application from MVC into ASP.net Core, I'm new to ASP.net Core. In MVC we have BundleConfig.cs
and in there we add references to our css and js files, how does it work in ASP.net Core? Let's say that I created a test.js
and a MyStyle.css
class, which is the best way to add references to it in every view? Should I place the .js
and .css
files inside wwwroot/js
and wwwroot/css
?
Upvotes: 31
Views: 72930
Reputation: 142
I put the CSS files at ~/wwwroot/css
, and the JavaScript files at ~/wwwroot/js
. Then I followed the format of the default _Layout.cshtml file.
<head>
. . .
<link type="text/css" rel="stylesheet" href="~/css/myCSS.min.css" />
. . .
</head>
<body>
. . .
<script src="~/js/myJS.min.js" asp-append-version="true"></script>
@RenderSection("Scripts", required: false)
. . .
</body>
Upvotes: 0
Reputation:
Static files such as Image files, CSS files and JavaScript JS files does not work in ASP.Net Core unless it is placed in proper location with the project and also some settings are set. And add this line in start up.css befor routing.
app.UseStaticFiles();
Upvotes: 0
Reputation: 2805
I added the references inside the _Layout
view, inside the <environment>
tags:
<environment names="Development">
<link rel="stylesheet" href="~/css/MyCss.css" />
</environment>
If anyone knows a better way I would welcome it
Upvotes: 33
Reputation: 151
In _layout:
@await RenderSectionAsync("Styles", required: false)
Then your view:
@section Styles{ your CSS }
Information from: https://dev.to/amjadmh73/loading-custom-css-files-in-razor-pages-4no9
Upvotes: 5
Reputation: 41
It might be a bit late to answer the question, but for the ones who come here via Google: I found that adding asp-append-version="true"
worked for me, as all the other options given in the other answers were already provided in _Layout.cshtml
.
Upvotes: 4
Reputation: 129
The better way to do it is to use: app.UseStaticFiles();
inside startup.cs
before routing.
Upvotes: 11
Reputation: 1033
I put the JS and CSS files in an assets folder in the wwwroot
folder of my application and then used link tags in my _Layout.cshtml
to bring in the styles. Steven Sanderson has part a of a blog post where he talks about adding third party libraries here.
You could also do some sort of setup using webpack. I admit, this topic is not very straight forward.
Upvotes: 2