使用 .NET MVC 控制器操作作为 HTML 的源

发布于 2024-09-05 22:08:20 字数 351 浏览 4 评论 0原文

我试图在页面上显示与我的数据库中的用户关联的图片(图片字段的数据类型为image) - 不幸的是,下面的代码无法做到这一点。

HTML

<img src="/User/Picture/1" />

控制器操作

public byte[] Picture(int id){
    UserRepository r = new UserRepository();
    return r.Single(id).logo.ToArray();
}

I'm trying to display the picture associated with a user in my database (the picture field's data type is image) on a page - unfortunately the code below fails to do that.

HTML

<img src="/User/Picture/1" />

Controller Action

public byte[] Picture(int id){
    UserRepository r = new UserRepository();
    return r.Single(id).logo.ToArray();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

玩套路吗 2024-09-12 22:08:20

问题已解决

抱歉,我对此没有足够的了解!

需要做的就是让控制器操作返回 FileContentResult

public FileContentResult Picture(int id)
{
    UserRepository r = new UserRepository();   
    return new FileContentResult(r.Single(id).logo.ToArray(), "image/jpeg");
}

PROBLEM SOLVED

Apologies, I didn't read up enough on this!

All that needed to be done was make the Controller Action return FileContentResult

public FileContentResult Picture(int id)
{
    UserRepository r = new UserRepository();   
    return new FileContentResult(r.Single(id).logo.ToArray(), "image/jpeg");
}
掌心的温暖 2024-09-12 22:08:20

这个问题有很多有用的答案。您可能需要与 FileContentResult 相关的答案。

简而言之,您需要返回适当的 ActionResult,而不仅仅是字节数组。

This question has a lot of useful answers. You probably need the FileContentResult-related answers.

In short, you need to return appropriate ActionResult, and not just array of bytes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文