Reputation: 105
I please need help to get my image to display correctly in the tag that is created in a literal control.
foreach (DataRow dr in dt.Rows)
{
string productName = dr["PRO_Name"].ToString();
string productPrice = dr["PRO_Price"].ToString();
byte[] productImg = (byte[])dr["PRO_Img"];
string sProduct = @"<div class='four-shop columns isotope-item'>
<div class='shop-item'>
<figure>
//I need the image from the data base here:
<img src='" + productImg + "' alt='' />
<figcaption center code herelass='item-description'>
<h5>" + productName + "</h5>
<span>R" + productPrice + "</span>
<a href='#' class='button color'>Add to Cart</a</figcaption>
</figure>
</div>
</div>";
//Im using a literal control to create the DIV dynamically for each product in the database.
productPanel.Controls.Add(new LiteralControl(sProduct));
}
Upvotes: 0
Views: 1444
Reputation: 854
Try this
View:
<img src="@Url.Action("GetImg", "Home", new {id= Model.id})" alt="" width="150" height="200"/>
Controller:
public FileContentResult GetImg(int id)
{
byte[] byteArray = new Model().GetImgByID(id);
if (byteArray != null)
{
return new FileContentResult(byteArray, "image/png");
}
else
{
//something failed, image not found!
return null;
}
}
Upvotes: 0
Reputation: 1698
You may use a generic handler (.ashx)
that get productName and use Context.WriteBinary()
method in ashx
file. You should pass productName
to ashx
as a query string:
<img alt="Product image" src="~/somewhere/ImageHandler.ashx?productName=" + productName + "/>"
Upvotes: 1
Reputation: 13003
You should put the URL of your image in the img
's src
attribute and not a byte
array as you do now:
//Wrong:
byte[] productImg = (byte[])dr["PRO_Img"];
<img src='" + productImg + "' alt='' />
In order to achieve it, take a look at this answer about how to create an ASP.NET ASHX Handler and eventually retrieve the image using a URL:
Display image from database in ASP.net with C#
Upvotes: 0
Reputation: 600
Depending on your browser needs and image size (I don't recommend it for large files), you may embed it as a base64 string. Look at: Embedding base64 images
Upvotes: 0