displaying image from db in Razor/MVC3

僤鯓⒐⒋嵵緔 提交于 2019-12-17 16:08:16

问题


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"/>    
        }

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.

What am I doing wrong?

Thanks in advance for your help and time

UPDATE

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>

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;
        }
    }

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


回答1:


Two possibilities.

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");
}

and then:

<img src="@Url.Action("GetImage", "SomeController", new { id = item.Id })" alt="@item.CountryName" /> 

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.


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" />

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



来源:https://stackoverflow.com/questions/9149430/displaying-image-from-db-in-razor-mvc3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!