Dynamically Load Image in ASP.NET-MVC3 with jQuery

This article will demonstrate you how to load images dynamically, fast at runtime on button click without post back.

Many approaches to do this but I will prefer load image using Ajax call. Usually in such case we put Ajax call get name of image and place it in to div or any place holder. This method may be bit slowly as one Ajax request and when you are putting image in to div again image has to come from server that is one more trip to server.  Overall performance will be bit slowly. Now to overcome this, instead of calling image name get string of byte array of image using Ajax call and convert that byte array string into image in Ajax response this approach will be much faster.

When to use this approach?
This approach will be useful when you have to load some images on button click without post backing page with good performance.

Here is code

Convert Image to binary

public JsonResult getImage()
    FileStream fileStream = new FileStream(@"C:\Projects\MVC4\sample1\sample1\Content\Images\1.jpg", FileMode.Open, FileAccess.Read);
    byte[] buffer = new byte[fileStream.Length];
    fileStream.Read(buffer, 0, (int)fileStream.Length);
    string str = System.Convert.ToBase64String(buffer, 0, buffer.Length);
    return Json(new { Image = str, JsonRequestBehavior.AllowGet });

Instead of sending byte array we are converting byte array to base64string and pass a string. Now catch string in Ajax response and convert this string into image.

 function LoadImage()
            type: 'POST',
            url: 'LoadImage/getImage',
            async: false,
            success: function (Image) {
                if (Image != '') {
                    var oImg = document.createElement("img");
                    oImg.setAttribute('src', 'data:image/png;base64,' + Image.Image);
This entry was posted in jQuery, MVC and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s