【问题标题】:How to display image from SQL image table that has imagepath如何显示具有图像路径的 SQL 图像表中的图像
【发布时间】:2017-08-07 11:08:33
【问题描述】:

我正在处理我的MVCOnlineShop 项目,我创建了一个产品列表页面,现在我想为每个产品显示一个图像,所以我在SQL 中创建了一个image 表,其中imageIDimagepath,在product 表中我添加了imageID,我已经搜索了如何从数据库中获取图像,但不太了解,所以请你帮我看看我的actionresult我的controller

这是我的productListPartialView

@model MVCOnlineShop.Models.Category

@{
    ViewBag.Title = "ProductList";
}

<script src="~/Scripts/Productjs/bootstrap.min.js"></script>
<script src="~/Scripts/Productjs/jquery.js"></script>
<link href="~/Content/Productcss/bootstrap.min.css" rel="stylesheet">
<link href="~/Content/Productcss/2-col-portfolio.css" rel="stylesheet">


<div class="container">

    <!-- Page Header -->
    <div class="row">
        @foreach (var Product in Model.Products)
        {
            <div class="col-md-6 portfolio-item">
                <a href="#">
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">
                </a>
                <h3>
                    <a href="#">@Html.ActionLink(Product.ProductName, "Details", new { id = Product.CategoryID })</a>
                </h3>
            </div>
        }
    </div>
</div>

此视图将显示每个产品,但使用相同的图像,我想更改它以获取数据库中的图像。

提前致谢 :)

【问题讨论】:

  • 你的“product”和“image”表之间是否有外键关系,使用那个“imageID”?那么你的 Product 应该有一个 Image 属性,以及你想要的图像路径。
  • 我在产品表中添加了 imageID,所以现在每个产品都会有 1 个或多个图像@HansKesting

标签: sql-server asp.net-mvc database entity-framework razor


【解决方案1】:

假设每个产品至少有一个图像(否则您需要检查它是否存在),并且您在 EF 模型中使用延迟加载(否则您将需要“包含”Images 属性)更改此:

<img class="img-responsive" src="http://placehold.it/700x400" alt="">

进入这个:

<img class="img-responsive" src="@Product.Images.First().Imagepath" alt="">

您可能需要更改各种属性的拼写,我不得不猜测它们。

【讨论】:

  • 我应该在控制器中添加任何东西吗?
  • @Ahmad 如果您使用实体框架并启用了延迟加载(这是默认设置),那么可能不会。你有什么错误吗?
  • 它说我的模型没有 First 的定义
  • 那么您在视图中缺少System.Linq 的“使用”
  • 得到这个:CS1061: 'MVCOnlineShop.Models.Image' does not contain a definition for 'First' and no extension method 'First' accepting a first argument of type 'MVCOnlineShop.Models.Image' could be found (are you missing a using directive or an assembly reference?)
猜你喜欢
  • 1970-01-01
  • 2016-03-09
  • 1970-01-01
  • 1970-01-01
  • 2011-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多