Automatically Adding CSS and JavaScript Files to .Net Core Layout Views

Previously, with the standard .NET platform, we were able to include CSS and JS files based on action and controller names using code like this:

string scriptSource = Url.Content(string.Format("~/js/page/{0}/{1}.js", controllerName, actionName));
if (System.IO.File.Exists(Server.MapPath(scriptSource)))
{
  <script type="text/javascript" src="@scriptSource"></script>
}

We would insert these codes in the Layout and it worked as long as the js folder and file names matched the controller and action names.

Recently, I upgraded the project to .NET Core (2.1) and implemented dependency injection in the BaseController to access the Server.MapPath value. However, I encountered difficulties reaching from the _Layout view to the BaseController or codebehind to get Server.MapPath. If anyone has successfully accomplished this, please share your solution.

Answer №1

If you are working with ASP.NET Core, it's important to note that the traditional Server.MapPath method is not recommended. A better practice is to utilize the IHostingEnvironment interface.

For instance, in the _Layout.cshtml file, consider implementing the following:

@using Microsoft.AspNetCore.Hosting
@inject IHostingEnvironment environment
@{
    string path = string.Format("js/page/{0}/{1}.js", controllerName, actionName);
}
@if (System.IO.File.Exists(System.IO.Path.Combine(environment.WebRootPath, path)))
{
    <!-- The file exists here... -->
}

In your controller class, you can inject the IHostingEnvironment through the constructor like this:

public class HomeController : Controller
{
    private readonly IHostingEnvironment _environment;

    public HomeController(IHostingEnvironment environment)
    {
        _environment = environment;
    }

    public IActionResult Index()
    {
        string path = System.IO.Path.Combine(_environment.WebRootPath, "js/page/...");

        return View();
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery and CSS animation implemented on website performs flawlessly on all browsers, with the exception

I have recently started learning jQuery and I am facing an issue with the website linked below. It works perfectly in Firefox, Chrome, and Opera but not in Safari. <head> <meta charset="UTF-8"> <meta name="viewport" content="width=devic ...

Unable to change Bootstrap variables within a Next.js project

I'm having trouble changing the primary color in Bootstrap within my NextJS project. I've tried different methods but nothing seems to work as expected. Here is the code snippet from my "globals.scss" file that I imported in "_app.js": $primary: ...

The elements in Dynamically generated ChartJs do not align with the bottom of the y-axis

I'm experiencing some unusual behavior with bars or risers in a dynamically generated Chartjs chart. They are not starting at point 0 on the y-axis and some of them are not displaying at all. Despite trying various solutions from different sources, i ...

Retrieving data from an HTML input tag and storing it in a variable

I'm currently working on a project that involves reading the contents of an uploaded file through an input tag and storing it in a variable. My goal is to then use an algorithm to decrypt the .txt file: <input type="button" value="decrypt" id="dec ...

Tips for aligning divs side by side with smaller divs stacked below them

I have a collection of dynamically generated divs that act as panels for selecting different options. These divs can be categorized into two types: regular and short. The height of the regular divs is determined using JavaScript to match the height of the ...

Unable to input text using Python Selenium in a textbox

Currently, I am attempting to input text into a specific textarea HTML element using Python Selenium: <div class="spk-c spH-d"><div id="gwt-uid-23" class="sppb-a"> <div class="sppb-b spk-b">For example, flowers or used cars</div> & ...

Exploring the concept of using variables and understanding variable scope in AJAX and JavaScript

Struggling with using variables in AJAX. Attempting to have var x store data from var data but it keeps showing as undefined in the console log. Any tips on how to fix this issue? EDIT: The variable x needs to be accessed later in the code, not just for ...

"The application is experiencing issues with loading styles correctly when using jQuery append (Fiddler has been

When attempting to load a div tag using the .append() method, the styles are not loading correctly. Here's the code that was tested: <section id="year-2020" class="tab-panel"> <div class="row accordion"> <header> ...

NodeJS is constantly refreshing the data in the database table

Every day, I use a cron job to scrape data and insert it into a database. However, I'm facing an issue where the database results on the server do not refresh themselves after new data is inserted. I've come across 2 solutions here, but one was ...

The CORS policy has blocked access to the XMLHttpRequest at 'http://github/..file.json' due to its origin being 'null'

Recently, I attempted to request a JSON file hosted on GitHub (for example: ). What made my situation different from this question is that I was using pure javascript without jQuery to make the AJAX call. Here's the snippet from my index.js file: fu ...

"angular-seed's web-script.js and cross-origin resource sharing (cors

I'm having trouble for the second day... I'm attempting to retrieve some json from an external domain, but I'm facing CORS issues. I believe that the problem lies with my node.js server not sending Origin: http://api.bob.com I've res ...

Having trouble understanding how to create a continuous loop for a CSS animation within the KreatureMedia Layerslider

Currently, I am using KreatureMedias Layerslider and trying to make a fullwidth wave bob up and down. This is what I have at the moment... <img class="ls-layer" data-ls="durationin:1500;scalein:1.1;offsetxin:-50;loopcount:-1;loopoffsetx:0sw;loopoffset ...

The grayscale effect is not functioning on the default web browser of an Android device

I have implemented a grayscale effect for an image using the following CSS code snippet: img.grayscale { filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\&apo ...

Utilizing Functions within Arrays and Exploring Time Intervals for Optimization

I am currently working on a game development project where the game involves answering questions within a specific time frame. Each question should be answered within 10 seconds before resetting for the next one. I'm fairly new to JavaScript and would ...

Storing JavaScript functions in a MySQL database

Is there a way to save the output from a JavaScript function to MySQL? var macs = { getMacAddress : function() { document.macaddressapplet.setSep( "-" ); return (document.macaddressapplet.getMacAddress()); } } ...

A guide to updating a button in Angular:

Currently, I have implemented a directive that displays 3 tabs at the bottom. However, I am curious to know if it is possible to swap out "exterior" for "interior" based on whether I am on the exterior or interior page. For example, when on the exterior ...

Unable to submit /api/sentiment

I'm currently troubleshooting the /api/sentiment endpoint in postman and encountering a "cannot POST" error. I have confirmed that the routes are correct and the server is actively listening on port 8080. Interestingly, all other endpoints function wi ...

Issues with Google API Column chart example in jsfiddle demonstration are hindering its functionality

I'm attempting to make the Google Column Chart example provided here function properly. Here is my effort: http://jsfiddle.net/dwNE4/ (Note: I'm having some difficulty getting it to load) This is the code from the fiddle: HTML <script src=&q ...

A different approach to database monitoring instead of using setInterval() - Meteor.js

To create a scroll-down message feed when the number of records changes or when a new message is inserted into the document, the approach needs to be simple and efficient. Instead of using setInterval to continuously check for database changes, we can con ...

What are the steps to upgrade to Bootstrap 4 in Laravel 5.5?

I am looking to transition to Bootstrap 4 in Laravel 5.5, Previously, I ran: composer require laravelnews/laravel-twbs4 However, I encountered layout issues in my "auth view" so I tried this: php artisan preset bootstrap4-auth Unfortunately, the p ...