如何将VarBinary映像从数据库检索到MVC视图

Ruh*_*tas 4 asp.net-mvc entity-framework sql-server-2008 asp.net-mvc-4

我将图片存储到数据库中,其类型为VARBINARY(MAX),如下所示: 在此处输入图片说明

这是我自动生成的模型文件Resim.cs

namespace ResimCek.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Resim
    {
        public Resim()
        {
            this.KelimeTuru = new HashSet<KelimeTuru>();
        }

        public int Id { get; set; }
        public int KelimeId { get; set; }
        public int SozlukTuruId { get; set; }
        public byte[] Adi { get; set; }
        public string Aciklama { get; set; }

        public virtual ICollection<KelimeTuru> KelimeTuru { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的控制器代码,当我键入“ xxxxxxxx / image / show / 2”时,我得到NullReference异常(但是我有一个id = 2的记录):

public ActionResult Show(int id)
{
    SozlukEntities db = new SozlukEntities();
    KelimeTuru kelime = db.KelimeTuru.Find(id);
    var imagedata = kelime.Resim.Adi;//Gets NullReference exception

    return File(imagedata, "image/jpg");
}
Run Code Online (Sandbox Code Playgroud)

最后这是我的视图代码:

<img src='<%= Url.Action( "show", "image", new { id = ViewData["Id"] } ) %>'>
Run Code Online (Sandbox Code Playgroud)

您能帮我在视图中显示我的照片吗?

小智 5

尝试这个 :

      public FileContentResult Show(int id)
          {
           SozlukEntities db = new SozlukEntities();
           KelimeTuru kelime = db.KelimeTuru.Find(id);
           var imagedata = kelime.Resim.Adi;

            return File(imagedata, "image/jpg");
       }
Run Code Online (Sandbox Code Playgroud)

<img src='<%= Url.Action( "show", "image", new { id = Model.Id } ) %>'> //Or be sure that you passed the id
Run Code Online (Sandbox Code Playgroud)