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.

2
  • 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 Commented Nov 22, 2018 at 14:47
  • Puppies will die if you try to use Server.MapPath in .Net Core. Look here Commented Nov 22, 2018 at 14:51

1 Answer 1

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();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.