JTApps JTApps - 1 year ago 64
Ajax Question

Display an image in a table row using Ajax/MVC

Cutting right to the chase, I've got something like this in my Controller:

return base.File(getSomeImageBitmap, "image/jpeg");

Which displays the image just fine in a new window using
. However, I want to populate the image directly into the table when a link is clicked. So, I tried this approach:

@Ajax.ActionLink("View", "Image", "Controller", new { id = t.id, id2 = t.id2},
new AjaxOptions { UpdateTargetId = "myImage", HttpMethod = "GET" }
<div id="myImage"></div>

is an object in the Model Array, this approach has two downsides. First, it displays the un-encoded bitmap as text, not an image. Second, it populates the data into the first div in the table every time.

My next strategy will be to create a PartialView and generate unique DIV ids so they can be inserted using
, but I have no idea if I can make it work like that.

Finally, I've tried:

<img src="@Url.Action("Image", "Controller", new { id = t.id, id2 = t.id2 })" alt="Some Image" />

Which works perfectly, minus the fact that it queries my webservice for up to 500 images all at once. I can't have that happen, I only want to retrieve the image when some arbitrary link is clicked. Is this possible? Jquery and Ajax are all fair game.

Answer Source

The problem is, your code is going to generate more than one div with id "myImage". that is not valid HTML. Id values should be unique.

I suggest you use a normal link and write your one jQuery code to handle the loading of the image when the link is clicked.

 @Html.ActionLink("View", "Image", "Home",  new { id = t.id, id2 = t.id2},
                                                                  new {@class="linkView"})
 <img class="imagePreview"/>

This will render a normal link with css class linkView and and an image tag with css class imagePreview.

Now listen to the click event on these link, prevent the default click behavior ( navigating to the href value), update the image src attribute.

You may use the closest() method to get a reference to the current table row (where the link belongs to ) and use find() method to get a reference to our image.


        var _this=$(this);


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download