I am trying to display an image in a view.
Here I add an image in SQL Server Express (price is defined as int and picture is a varbinary(MAX) column):
insert into products (price, picture)
select 499, BulkColumn
from Openrowset(Bulk 'C:\Users\tally\Pictures\harddisk-275-183.jpg', Single_Blob) as img
Here I have defined properties:
public class ProductsModel
{
public Image ProductImage { get; set; }
public int ProductPrice { get; set; }
}
I get the data from the database using this controller method:
[HttpGet]
public IActionResult Products(ProductsModel objProductsModel)
{
string conStr = "Data Source=.\\SQLEXPRESS; Initial Catalog=Onlineproducts; Integrated Security=True";
SqlConnection con = new SqlConnection(conStr);
con.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter(new SqlCommand("select * from products", con));
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
if (dataSet.Tables[0].Rows.Count == 1)
{
Byte[] data = new Byte[0];
data = (Byte[])(dataSet.Tables[0].Rows[0]["picture"]);
MemoryStream mem = new MemoryStream(data);
objProductsModel.ProductImage = Image.FromStream(mem);
objProductsModel.ProductPrice = Convert.ToInt32(dataSet.Tables[0].Rows[0]["price"]);
return View(objProductsModel);
}
return View(objProductsModel);
}
Here I try to display both image and price in the view:
@model Nettbutikk.Models.ProductsModel
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link rel="stylesheet" href="~/css/products.css" />
</head>
<body>
<p><h1>Products</h1></p>
<hr />
<div class="responsive">
<div class="gallery">
<div>@Html.DisplayFor(ProductsModel => ProductsModel.ProductImage)</div>
<div class="desc">Kr @Html.DisplayFor(ProductsModel => ProductsModel.ProductPrice)</div>
</div>
</div>
</body>
</html>
Price is displayed on webpage as it should be but the image is not.
Maybe to display the image I should select something else than DisplayFor(...)? Please help me.
DisplayForlike that, easiest to create a separate request. Create a separate controller action that returns the raw image data, then call said action withHtml.Content()(or just a regular img tag).