Dowemo
0 0 0 0


Question:

I've a model with a byte array image file that I want to show on the page.

How can I do that without going back to the Database?

All the solutions that I see use an ActionResult to go back to the database to retrieve the image, but I already have the image on the model...


Best Answer:


I recommend something along these lines, even if the image lives inside of your model.

I realize you are asking for a direct way to access it right from the view and many others have answered that and told you what is wrong with that approach so this is just another way that will load the image in an async fashion for you and I think is a better approach.

Sample Model:

[Bind(Exclude = "ID")]
public class Item
{
    [Key]
    [ScaffoldColumn(false)]
    public int ID { get; set; }
    public String Name { get; set; }
    public byte[] InternalImage { get; set; } //Stored as byte array in the database.
}

Sample Method in the Controller:

public async Task<ActionResult> RenderImage(int id)
{
    Item item = await db.Items.FindAsync(id);
    byte[] photoBack = item.InternalImage;
    return File(photoBack, "image/png");
}

View

@model YourNameSpace.Models.Item
@{
    ViewBag.Title = "Details";
}
<h2>Details</h2>
<div>
<h4>Item</h4>
<hr />
<dl class="dl-horizontal">
    <img src="@Url.Action("RenderImage", new { id = Model.ID})" />
</dl>
<dl class="dl-horizontal">
    <dt>
        @Html.DisplayNameFor(model => model.Name)
    </dt>
    <dd>
        @Html.DisplayFor(model => model.Name)
    </dd>
</dl>
</div>



Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs