asp.net-mvc-3 – 在Razor / MVC3中显示db的图像

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-3 – 在Razor / MVC3中显示db的图像前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在db中有一个表,其中包含以下内容: – CountryID,CountryName和Country Image.

现在我试图在索引中显示图像,我在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;
        }
    }

但是我看不到图像正确.

我究竟做错了什么?

提前感谢您的帮助和时间

UPDATE

好,所以我在视图中实现了以下内容

<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没有被击中

解决方法

两种可能性

写一个控制器动作,而给定一个图像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属性.随后将在控制器操作中检索此操作.

另一种可能性是使用data URI scheme将图像嵌入base64字符串,但是它可能不被所有浏览器广泛支持

<img src="data:image/jpg;base64,@(Convert.ToBase64String(item.Image))" alt="@item.CountryName" />

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

原文链接:https://www.f2er.com/aspnet/246401.html

猜你在找的asp.Net相关文章