Pedro Santos
Pedro Santos

Reputation: 3

mvc controller json return

i want to return an image in base64 from my controller to view using json.

public JsonResult changeProfile()
        {
            var userID = ((SessionModel)Session["SessionModel"]).UserID; // get current user id
            TBL_User item = _context.TBL_User.Find(userID);
            UserModel model = new UserModel();
            model.UserID = userID;
            model.BinaryPhoto = item.BinaryPhoto;

            return Json(new
            {
                ??????????????'
            },
                JsonRequestBehavior.AllowGet);
        }

what can i put there to return my image and display in the view? thanks

Upvotes: 0

Views: 63

Answers (1)

Hien Nguyen
Hien Nguyen

Reputation: 18975

Update controller

  public JsonResult changeProfile()
            {
                var userID = ((SessionModel)Session["SessionModel"]).UserID; // get current user id
                TBL_User item = _context.TBL_User.Find(userID);
                UserModel model = new UserModel();
                model.UserID = userID;
                model.BinaryPhoto = item.BinaryPhoto;

                var base64 = Convert.ToBase64String(model.BinaryPhoto); 
                var imgsrc = string.Format("data:image/jpg;base64,{0}", base64);

                return Json(new
                {
                    Image = imgsrc 
                },
                    JsonRequestBehavior.AllowGet);
            }

Update src for image in ajax success

$.ajax({
      url: "/changeProfile",  
      success: function(data) {
          $(".img-circle").attr('src', data.Image);
      }
   });

Upvotes: 0

Related Questions