2

I use ShowImage() method of the Home controller to show the image generated on fly.

HTML

<img src='@Url.Action("ShowImage", "Home" )' width="267" height="500">

Now I would like to execute some action with AJAX and update that image like this

 $.ajax({
     type: "POST",
     url: '@Url.Action("UpdateUser", "Home")',
     contentType: "application/json; charset=utf-8",
     data: JSON.stringify(params),
     dataType: "json",
     success: function (data) {
         if (data.success.toString() == 'true') {

             // Is it possible update image using JavaScript?


         }
     }
 });

Is it possible to do? Thanks!

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
NoWar
  • 36,338
  • 80
  • 323
  • 498

3 Answers3

3

Your controller can return an Image with the base File method:

public ActionResult Image(string id)
{
     var myStream = new byte[0];
     // your code géneration....
     return File(myStream, "image/jpeg");
}

Than, you change the image src attribute:

$("#image").attr("src", "/MyController/Image/2");
Adriien M
  • 1,165
  • 7
  • 6
  • 1
    This is the complete answer, but I already commented once below your question ;) – Adriien M Jul 03 '14 at 12:04
  • I am confused on how this is the accepted answer as the OP was asking for help using AJAX to change image. This seems to only show how to load image with page load, how do you refresh with AJAX and JSON? – eaglei22 May 17 '17 at 20:55
3

Add an id to your image:

<img id="anImage" src='@Url.Action("ShowImage", "Home" )' width="267" height="500">

Then in your success handler set it as follows:

$('#anImage').attr("src", 'success.png');

If your image is returned as json from your controller, pull it from the data instead:

$('#anImage').attr("src", data.image);
hutchonoid
  • 32,982
  • 15
  • 99
  • 104
0

Try this for pure javascript

document.getElementById("id of ur img").src="your source goes here";
Unknownman
  • 473
  • 3
  • 9