在 Razor/MVC3 中显示来自数据库的图像 [英] displaying image from db in Razor/MVC3

查看:35
本文介绍了在 Razor/MVC3 中显示来自数据库的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a table in the db, which has the following :- CountryID, CountryName, and CountryImage.

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

Now I am trying to display the image in the index and I have the following in the View :-

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

然后在 ViewModel 我有:-

and then in the ViewModel I have :-

        public FileContentResult GetImage(byte[] image)
    {
        if (image != null)
            return new FileContentResult(image, "image/jpeg");
        else
        {
            return null;
        }
    }

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

However I cannot see the image properly.

我做错了什么?

提前感谢您的帮助和时间

Thanks in advance for your help and time

更新

好的所以我在视图中实现了以下内容:-

Ok So I have implemented the following in the View :-

        <td>
        @if (item.Image != null)
        {
            <img src="@Url.Action("GetImage", "CountryController", new { id = item.CountryID })" alt="@item.CountryName" />             
        }
    </td>

在 CountryController 中:-

and in the 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

but when I try to debug the code, the ActionResult GetImage is not being hit

推荐答案

两种可能性.

编写一个控制器动作,给定一个图像 ID 将返回这个图像:

Write a controller action instead which given an image id will return this image:

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 属性.这将随后在负责该操作的控制器操作中检索.

Obviously now in your initial model you don't need the Image property. This will be retrieved subsequently in the controller action responsible for that.

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

Another possibility is to use data URI scheme to embed the images as base64 strings but it might not be widely supported by all browsers:

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

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

You don't need a controller action in this case as the images are directly embedded into your markup as base64 strings.

这篇关于在 Razor/MVC3 中显示来自数据库的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆