csefaruk
csefaruk

Reputation: 191

HTML Img tag reload with Javascript

I try to load a image with Combo selection change:

Normally i can load a image in follow way:

Razor View :

<img id="imgPhotoIcon" src="@Url.Action("GetPhoto", "Contractor", new { id = Model.ContactPersonnelID })" alt="Photo" style="width:150px; height:150px" />

Controller Part :

public Image GetPhoto(int id)
        {
            ContactPersonnel oContactPersonnel = new ContactPersonnel();
            oContactPersonnel = oContactPersonnel.GetWithImage(id, (Guid)Session[SessionInfo.wcfSessionID]);
            if (oContactPersonnel.Photo != null)
            {
                MemoryStream m = new MemoryStream(oContactPersonnel.Photo);
                System.Drawing.Image img = System.Drawing.Image.FromStream(m);
                img.Save(Response.OutputStream, ImageFormat.Jpeg);
                return img;
            }
            else
            {
                return null;
            }
        }

Now i want to load image with combo selection change based on selected item any one help me

Upvotes: 1

Views: 212

Answers (1)

Nitin Varpe
Nitin Varpe

Reputation: 10694

basic problem here I think is you need to give url of image as a source of image so you need to return image url using json .Following is ajax method which would be called onchange of your combobox.Id is the input you want to pass to method.Or you can return base64string of byte array to ajax success

$.ajax({
                            cache:true,
                            type: "POST",
                            url: "@(Url.Action("GetPhoto", "Contractor"))",
                            data: "id=" + id,
                            success: function (data) {

  $('#imgPhotoIcon').attr('src', "data:image/jpg;base64," + data);

                                                   }
        });

Following is controller action

public Actionresult GetPhoto(int id)
        {
       //logic to get picture url goes here 
       // string picture=GetPictureUrl(id);

      byte[] imageByteArray = images;//Return byte array here
return Json(new { base64imgage =  Convert.ToBase64String(imageByteArray) }
                , JsonRequestBehavior.AllowGet);
        }

Hope It helps

Upvotes: 1

Related Questions