Reputation: 937
I have an ActionMethod which can return a Memorystream or byte[] of an image. This action method is called on ajax. Now I want to bind this image to an image tag src attribute.
public ActionResult GetBpChart(string Timespan)
{
var ObjMemoryStream = new MemoryStream();
try
{
ObjMemoryStream = MyModel.GetImage(Timespan);
}
catch (Exception Ex)
{
}
//return Content(Convert.ToBase64String(ObjMemoryStream.GetBuffer()));
//return Json(ObjMemoryStream.GetBuffer());
return File(ObjMemoryStream.GetBuffer(), "image/jpeg");
}
function GetChart() {
try {
$.ajax({
type: 'POST',
url: "myActionMethodurl",
data: {
Timespan: $('#ddlBpTimespan').val()
},
success: function (ImgSrc) {
// For Base64String
//$('#divBpChart').innerHTML = '<img src= "data:image/jpeg;base64," ' + ImgSrc + '"/>';
// For Json of byte[]
//$('#divBpChart').innerHTML = '<img src= "data:image/gif;base64," ' + ImgSrc + '"/>';
// For FileContentResult
$('#imgBpChart').attr('src', ImgSrc);
HideAjaxProgress();
}
});
} catch (E) {
}
}
I tried the above 3 combinations. But no luck. Can someone say what I am missing here or what's the correct way to achieve this
Upvotes: 1
Views: 3335
Reputation: 21231
From reading the .ajax() docs, I would say the simple answer is "no, you can't do that."
Luckily, you don't need to. Just create the relevant URL and update the target image's src
attribute:
function GetChart() {
try {
var ImgSrc = '/mycontroller/myActionMethodurl?timespan=' + $('#ddlBpTimespan').val();
$('#imgBpChart').attr('src', ImgSrc);
} catch (error) {
}
}
If you're coding this within a View, you can leverage the UrlHelper to help build the correct "base" URL:
function GetChart() {
try {
var ImgSrc = '@Url.Action("myActionMethodurl", "mycontroller")?timespan=' + $('#ddlBpTimespan').val();
$('#imgBpChart').attr('src', ImgSrc);
} catch (error) {
}
}
For a plain JavaScript method that seems to work, refer to Using jQuery's ajax method to retrieve images as a blob.
Upvotes: 2