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

标签 asp.net-mvc-3 c#-4.0 razor

我在数据库中有一个表,其中包含以下内容:- 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/

相关文章:

asp.net - VB 的 Razor View 不支持 @Model?

javascript - 如何使用 MVC4 Razor 在字符串中使用 @class

asp.net-mvc-3 - MVC3 - 使用 Razor 有条件地添加 id 元素

c# - 尝试在 ASP.NET MVC3 View 中将 EditorFor 与 ICollection<string> 一起使用?

asp.net-mvc-3 - 附加 .mdf 文件时的数据库 "cannot be opened because it is version 661"

c# - 如何在给定条件的情况下从递归层次结构返回节点路径?

asp.net-mvc - 如何更改MVC3中的Html.RadioButtonFor选择?

asp.net-mvc-3 - ASP.NET MVC 不会将 aspx 页面中的模型对象转换为适当的已将模型发送到此页面的方法

jquery - 使用 asp.net mvc 3 时如何将 jQuery load() 加载到动态创建的元素中?

c# - 如何在 PDF 文件的文件属性的详细信息选项卡中添加关键字