【问题标题】:Including Css and Js files programatically in .Net Core Layout View在 .Net Core 布局视图中以编程方式包含 Css 和 Js 文件
【发布时间】:2019-04-25 06:12:39
【问题描述】:

当我们使用标准的 .net 平台时,我们能够通过操作包含 css 和 js 文件,并通过这样的代码包含控制器名称;

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>
}

我们将这些代码放在布局中,当您将 js 文件夹命名为与控制器名称相同且 js 文件与操作名称相同时,它可以正常工作..

前段时间我将项目升级到 .Net Core(2.1) 并对 BaseController 进行了依赖注入以获取 Server.MapPath 值,但我无法从 _Layout 视图到达 BaseController 或代码隐藏以获取 Server.Mappath。 . 如果你们中的任何人能成功,请告诉我。

【问题讨论】:

  • 为什么不直接在源代码中使用 tilda - 你实际上不必在布局中使用 server.mappath,因为它会在页面渲染时自行解决
  • 如果你尝试在 .Net Core 中使用 Server.MapPath,小狗会死。 Look here

标签: javascript c# css asp.net-core


【解决方案1】:

在 ASP.NET Core 中,我们不使用 Server.MapPath。我们想改用IHostingEnvironment

在文件_Layout.cshtml,你可以试试:

@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... -->
}

在控制器中,可以通过构造函数传递:

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

【讨论】:

    猜你喜欢
    • 2017-03-13
    • 1970-01-01
    • 2013-09-30
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    • 2012-07-15
    • 1970-01-01
    相关资源
    最近更新 更多