【问题标题】:Display Image from Path in Asp.Net Core and Razor view?在 Asp.Net Core 和 Razor 视图中显示来自路径的图像?
【发布时间】:2019-07-30 04:26:39
【问题描述】:

我正在尝试在 MVC View Razor 网页中显示项目的图片。

以下操作无效。 ImageLocation 只有图片编号文件名。

Example: 
Product1.jpg
Product2.jpg
Product3.jpg
Product4.jpg

视图不起作用,只需要显示一张产品图片:

@model ElectronicsStore.Models.Product

@{
    ViewData["Title"] = "Details";
}

<h2>Details</h2>

<div>
    <h4>Product</h4>
    <hr />
    <dl class="dl-horizontal">

        <dt>
            <img src="~/images/@Url.Content(Model.ImageLocation)" alt="Image">
        </dt>
        <dd>

        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.ProductDescription)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.ProductDescription)
        </dd>
    </dl>
</div>

这个解决方案还没有工作,因为它使用了以前版本的 mvc net How to display an image from a path in asp.net MVC 4 and Razor view?

【问题讨论】:

  • 检查路径的一个简单技术是,一旦页面被渲染,查看为 img 标签生成的 html。
  • 您是否将您的图片文件夹放在`wwwroot` 中并在启动时使用app.UseStaticFiles();?按F12查看是否有&lt;img src="/images/Product1.jpg" alt="Image"&gt;这样的元素。

标签: c# razor asp.net-core asp.net-core-mvc asp.net-core-2.0


【解决方案1】:

这是获取目录中的所有图像。当然,您可以根据需要对其进行调整。

我用过这样的东西:

var images = Directory.EnumerateFiles(Server.MapPath("Path"))
                             .Select(fn => "Path" + Path.GetFileName(fn));

并显示它我会使用:

foreach (var image in (IEnumerable<string>)images)
{
      //Your logic here eg:
      <img class="img" src="@Url.Content(image)" />
}

根据您的需要调整它

【讨论】:

  • 我只需要显示一张产品图片,会检查这是否有效
猜你喜欢
  • 2021-09-29
  • 2013-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-26
  • 2018-12-11
  • 1970-01-01
相关资源
最近更新 更多