gpt4 book ai didi

asp.net-mvc-3 - 在 Razor/MVC3 中显示来自数据库的图像

转载 作者:行者123 更新时间:2023-12-04 00:45:04 25 4
gpt4 key购买 nike

我在数据库中有一个表,其中包含以下内容:- CountryID、CountryName 和 CountryImage。

现在我试图在索引中显示图像,我在 View 中有以下内容:-

        <td>
@if (item.Image != null)
{
<img src="@Model.GetImage(item.Image)" alt="@item.CountryName"/>
}

然后在 ViewModel 我有:-
        public FileContentResult GetImage(byte[] image)
{
if (image != null)
return new FileContentResult(image, "image/jpeg");
else
{
return null;
}
}

但是我无法正确看到图像。

我究竟做错了什么?

提前感谢您的帮助和时间

更新

好的所以我在 View 中实现了以下内容:-
        <td>
@if (item.Image != null)
{
<img src="@Url.Action("GetImage", "CountryController", new { id = item.CountryID })" alt="@item.CountryName" />
}
</td>

并在 CountryController 中:-
        public ActionResult GetImage(int id)
{
var firstOrDefault = db.Countries.Where(c => c.CountryID == id).FirstOrDefault();
if (firstOrDefault != null)
{
byte[] image = firstOrDefault.Image;
return File(image, "image/jpg");
}
else
{
return null;
}
}

但是当我尝试调试代码时,没有命中 ActionResult GetImage

最佳答案

两种可能。

编写一个 Controller Action ,而不是给定图像 id 将返回此图像:

public ActionResult GetImage(int id)
{
byte[] image = ... go and fetch the image buffer from the database given the id
return File(image, "image/jpg");
}

接着:
<img src="@Url.Action("GetImage", "SomeController", new { id = item.Id })" alt="@item.CountryName" /> 

显然现在在您的初始模型中您不需要 Image属性(property)。这将随后在负责该操作的 Controller 操作中检索。

另一种可能性是使用 data URI scheme将图像嵌入为 base64 字符串,但它可能不被所有浏览器广泛支持:
<img src="data:image/jpg;base64,@(Convert.ToBase64String(item.Image))" alt="@item.CountryName" />

在这种情况下,您不需要 Controller 操作,因为图像作为 base64 字符串直接嵌入到您的标记中。

关于asp.net-mvc-3 - 在 Razor/MVC3 中显示来自数据库的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9149430/

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