gpt4 book ai didi

javascript - 在 .Net Core 布局 View 中以编程方式包含 Css 和 Js 文件

转载 作者:行者123 更新时间:2023-11-29 23:13:19 24 4
gpt4 key购买 nike

当我们使用标准的 .net 平台时,我们能够通过这样的代码通过操作和 Controller 名称包含 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 文件夹命名为 Controller 名称并将 js 文件命名为 Action 名称时,它就可以工作了。

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

最佳答案

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

在 Controller 中,您可以通过构造函数传递它:

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

关于javascript - 在 .Net Core 布局 View 中以编程方式包含 Css 和 Js 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53433010/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com