@foreach (var item in Model)
{
<img src='ShowShowcaseImage/@Html.Encode(item.ProductID)' id='@item.ProductID' />
<b>@Html.DisplayFor(m => item.ProductName)</b>
<a href="#" class="enlargeImg" id="@item.ProductID">Enlarge</a>
}
<div id="EnlargeContent" class="content">
<span class="button bClose"><span>X</span></span>
<div style="margin: 10px;" id="imageContent">
</div>
<p align="center"></p>
</div>
//Popup javascript
$('.enlargeImg').bind('click', function (e) {
$.post('/Home/EnlargeShowcaseImage/' + $(this).attr('id'), null, function (data) {
document.getElementById("imageContent").innerHTML += data;
});
$('#EnlargeContent').bPopup();
});
});
//
C# method
public ActionResult EnlargeShowcaseImage(string id)
{
var imageData = //linq query for retrive bytes from database;
StringBuilder builder = new StringBuilder();
if (imageData != null)
builder.Append("<img src='" + imageData.ImageBytes + "' />");
return Json(builder);
}
I want to show pop up of enlarged image on click of enlarge link. Image is stored in bytes in database. Two images are stored in database for each product – one is thumbnail and the other is enlarged. I am showing thumbnail image and I want to show enlarged image on click of enlarge link. I can’t retrieve it from database.
So your question is about retrieving an image from a database, right? It has strictly nothing to do with ASP.NET MVC?
Unfortunately you haven’t told us whether you are using some ORM framework to access to your database or using plain ADO.NET. Let’s assume that you are using plain ADO.NET:
and if you are using some ORM it could be as simple as:
and then inside your controller action:
and it is inside your view that you should create an
<img>tag pointing to this controller action upon button click:But hardcoding the url to your controller action in javascript like this is very bad practice because when you deploy your application it might break. It might also break if you decide to change the pattern of your routes. You should never hardcode urls like this. I would recommend you generating this url on the server.
For example I see that you have subscribed to some
.enlargeImageelement. Let’s suppose that this is an anchor. Here’s how to properly generate it:and then adapt the click handler: