将字节数组转换为图像并在 Razor 视图中显示 [英] Convert Byte Array to image and display in Razor View

查看:26
本文介绍了将字节数组转换为图像并在 Razor 视图中显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 EF 4.1 Code First,为了简单起见,假设我有以下实体类:

I am using EF 4.1 Code First and for the sake of simplicity, let's say I have the following Entity class:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Byte[] Image { get; set; }
}

我已经成功地创建了一个工作创建视图,允许将一个人对象添加到数据库中.

I have managed to create a working Create View that allows the Addition of a Person object into the Database.

但是当我要显示一个人的详细信息时,我会卡在显示图像上.经过一番研究,我有以下几点:

But when I come to display the details for a Person, I get stuck on displaying the image. After doing some research, I have the following:

// To convert the Byte Array to the author Image
public FileContentResult getImg(int id)
{
    byte[] byteArray = DbContext.Persons.Find(id).Image;
    return byteArray != null 
        ? new FileContentResult(byteArray, "image/jpeg") 
        : null;
}

在我试图列出人员详细信息的视图中,我有以下内容来显示图像:

And in the View where I am attempting to list the Person details, I have the following to get the Image to display:

<img src="@Html.Action("getImg", "Person", new { id = item.Id })" alt="Person Image" />

但是上述方法不起作用,我的图像源[src] 属性返回空.

However the above is not working, my image source [src] attribute returns empty.

推荐答案

像这样:

<img src="@Url.Action("getImg", "Person", new { id = item.Id })" alt="Person Image" />

您需要 Url.Action 而不是 Html.Action 因为您只想生成 GetImg 操作的 URL.Html.Action 做了一些完全不同.

You need Url.Action and not Html.Action because you just want to generate an url to the GetImg action. Html.Action does something entirely different.

这篇关于将字节数组转换为图像并在 Razor 视图中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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