Display an image in a table row using Ajax/MVC
<p>Cutting right to the chase, I've got something like this in my Controller:</p>

<p><code>return base.File(getSomeImageBitmap, "image/jpeg");</code></p>

<p>Which displays the image just fine in a new window using <code>@Html.ActionLink</code>. However, I want to populate the image directly into the table when a link is clicked. So, I tried this approach:</p>

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

<p>Given <code>t</code> 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. </p>

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

<p>Finally, I've tried:</p>

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

<p>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.</p>

<p>EDIT: Went with the following solution, which supports hiding the image as well. It only lacks any kind of loading text:</p>

<pre><code>&lt;img hidden src="" alt="No Image" class="imagePreview" /&gt;
&lt;script type="text/javascript"&gt;
    // Handle clicking the View image link
    $(".linkView").click(function (e) {
        e.preventDefault();
        // The link being clicked
        var _this = $(this);
        // Find the closest imagePreview to the link
        var image = _this.closest("tr").find("img.imagePreview");

        if (image.is(':visible')) {
            // If the image is visible, hide it
            _this.text("View");
            image.hide();
        } else {
            // If image is not visible, show it
            _this.text("Hide");
            image.show();

            // If the image src has not been set, set it to the link href
            // By not clearing the src attribute, we can show/hide without loading the image again
            if (image.attr("src") == "") {
                image.attr("src", _this.attr("href"));
            }
        }
    });
&lt;/script&gt;
</code></pre>