首页 文章

使用ASP.NET核心的LazyLoad - 相对根路径?

提问于
浏览
0

What I'm trying to achieve:

使用LazyLoad的data-original属性,同时为我的相对根路径保留ASP.NET的〜/ path标识符!

What the problem is:

data-original属性不会将我的〜/转换为我的图像的相对根路径

A normal image path:

<img src="www/folder/file.png" />

ASP.NET Core path: 这需要 ~/ 告诉ASP.NET它是从根相对路径开始的

<img src="~/folder/file.png" />

LazyLoad's image

<img data-original="/folder/file.png" />

有没有人有任何经验让相对根路径与LazyLoad的 data-original 属性一起正常工作?

I've already tried doing this:

<img data-original="~/folder/file.png" />

但它不起作用

1 回答

  • 0

    我自己想出了答案 . 我决定在Controller中创建自己的相对根路径变量,然后将值返回到View中 . 那时我只需要使用Razor Markup插入变量并完成它!

    My Environment:

    • .NET Core 1.1

    • ASP.NET核心


    Controller:

    IHostingEnvironment service有两个特别感兴趣的属性: ContentRootPathWebRootPath . 出于我的目的,我将使用 ContentRootPath 因为我想访问相对根路径或换句话说 wwwroot

    private readonly IHostingEnvironment _hostingEnvironment;
    
    public HomeController(IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }
    

    确保将命名空间添加到文件中!

    using Microsoft.AspNetCore.Hosting;
    

    在我完成了我想要的控制器中的基础工作之后,在同一个文件中我只想要一个特定的页面来利用我的工作 . 为简单起见,它将在示例代码中表示为 Index .

    public IActionResult Index()
    {
        ViewBag.wwwRootPath = _hostingEnvironment.ContentRootPath;
        return View();
    }
    

    View:

    似乎Microsoft的.NET Core在运行时或构建时只将 ~/ 转换为相对根目录,如果它在元素中的 src 属性内 . 因此,那些使用第三方库或者您需要指定非 src 方式来调用文件的情况下,这个解决方案就足够了,直到它们增加了可扩展性 .

    我将使用 Question 中的示例作为解决方案的示例 . 因此,如前所述,此代码在应用程序中不起作用 .

    <img data-original="~/folder/file.png" />
    

    解决方案:

    <img data-original="@ViewBag.wwwRootPath/folder/file.png" />
    

    Note: 这对JavaScript和CSS也很有用!只需将 ViewBag.wwwRootPath 放在所需的文档中即可保持一致!

相关问题