加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-15 19:41:04 所属栏目:asp.Net 来源:网络整理
导读:我在db中有一个表,其中包含以下内容: – CountryID,CountryName和Country Image. 现在我试图在索引中显示图像,我在View中显示以下内容: td @if (item.Image != null) { img src="@Model.GetImage(item.Image)" alt="@item.CountryName"/ } 然后在ViewModel
我在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字符串.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读