displaying image from db in Razor/MVC3

前端 未结 1 1801
礼貌的吻别
礼貌的吻别 2020-12-05 16:04

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 follo

相关标签:
1条回答
  • 2020-12-05 16:35

    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.

    0 讨论(0)
提交回复
热议问题