【问题标题】:mvc controller json returnmvc控制器json返回
【发布时间】:2019-05-06 14:17:45
【问题描述】:

我想从我的控制器返回 base64 格式的图像以使用 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);
        }

我可以放什么来返回我的图像并在视图中显示? 谢谢

【问题讨论】:

  • BinaryPhoto 的类型是什么?
  • var base64 = Convert.ToBase64String(Model.BinaryPhoto); var imgsrc = string.Format("data:image/jpg;base64,{0}", base64);) @HienNguyen

标签: json asp.net-mvc model-view-controller


【解决方案1】:

更新控制器

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

在 ajax 成功更新图像的 src

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

【讨论】:

  • 我是什么输入 src 吗?
  • 改成$(".img-circle").attr('src', data.Image);