?Briella 2014-03-05 20:14 采纳率: 0%
浏览 37

使用AJAX显示图像

I am trying to display a picture that I am calling from the controller using AJAX, this is my code:

<div id="productImg" style="display:none;">

</div>


<script>
    function showPic(id) {

        $.ajax({
            type: "GET",
            url: "/Equipment/GetImage",
            data: { 'productId': id },
            success: function (data) {
                $("#productImg").html(data)

            }
        });
</script>

And the method on my controller looks like this:

public virtual FileContentResult GetImage(int productId) {
  Product prod = _db.Products.FirstOrDefault(p => p.ProductID == productId);
  if (prod != null) {
    return File(prod.ImageData, prod.ImageMimeType);
  } else {
    return null;
  }
}

What I am getting is a lot of code and not the image. What else could I try?

  • 写回答

2条回答 默认 最新

  • Lotus@ 2014-03-05 20:18
    关注

    You don't need to use AJAX for this. Images are separate resources for a page and are loaded as separate requests already. Just link to it:

    <div id="productImg">
        <img src="/Equipment/GetImage?productId=123" alt="Product" />
    </div>
    

    For making that happen dynamically in JavaScript, all you need to do is change that src value:

    function showPic(id) {
        $('#productImg img').src = '/Equipment/GetImage?productId=' + id;
    }
    

    As an aside, the reason your approach doesn't work is because what you're getting back from the server isn't HTML, it's the raw image data. The HTML to display an image is not the image data itself, it's just an img tag with a URL. (That URL can contain an encoded copy of the actual data, but it really doesn't need to in this case.)

    评论

报告相同问题?