简体   繁体   中英

How to add js and css files in ASP.net Core?

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 ?

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

The better way to do it is to use: app.UseStaticFiles(); inside startup.cs before routing.

回答这个问题可能有点晚了,但是对于那些通过 Google 来到这里的人:我发现添加asp-append-version="true"对我有用,因为其他答案中给出的所有其他选项已经在_Layout.cshtml提供。

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.

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

I put the CSS files at ~/wwwroot/cs, 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>

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM