1

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

2
  • Do you get a valid image back if you request the GetBpChart action directly? Commented Apr 13, 2015 at 5:25
  • Yes I do. I am getting the expected image on calling GetBpChart action directly. Commented Apr 13, 2015 at 5:38

1 Answer 1

2

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) {
    } 
}

Perhaps a better alternative?

For a plain JavaScript method that seems to work, refer to Using jQuery's ajax method to retrieve images as a blob.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.