2

When we were using standart .net platform we were able to include css and js files by action and controller name by a 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 were putting these codes in Layout and It was working when you name js folder same as controller name and js file same as action name..

For a while ago I upgraded project to .Net Core(2.1) and made dependecy injection to BaseController to get Server.MapPath value, but I couldn't reach from _Layout view to the BaseController or codebehind to get Server.Mappath.. If any of you could succeeded this please let me know.

Project Mayhem
  • 439
  • 5
  • 12
  • why not just use the tilda in the source - you don't actually have to use server.mappath in the layout as it will resolve itself when the page is rendered – Pete Nov 22 '18 at 14:47
  • Puppies will die if you try to use `Server.MapPath` in .Net Core. [Look here](https://stackoverflow.com/questions/49398965/what-is-the-equivalent-of-server-mappath-in-asp-net-core) – Crowcoder Nov 22 '18 at 14:51

1 Answers1

1

In ASP.NET Core, we don't use Server.MapPath. We want to use IHostingEnvironment instead.

In the file _Layout.cshtml, you could try:

@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)))
{
    <!-- file exist here... -->
}

In the controller, you can pass it via constructor:

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();
    }
}
Project Mayhem
  • 439
  • 5
  • 12
Tân
  • 1
  • 15
  • 56
  • 102