You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过jQuery Ajax将Controller动态生成的PNG图片展示到View视图

功能实现修复方案

现存错误点

  • jQuery选择器书写错误:$("rsDiagram")缺少ID选择器必须的#前缀,无法正确匹配到页面上的img元素
  • 图片地址拼接错误:给src属性赋值时,末尾额外加了多余的双引号,会导致base64格式的图片地址非法,浏览器无法识别
  • 变量未定义:回调函数中直接使用rs变量,如果没有提前获取对应DOM元素,会抛出未定义错误
  • 可选优化点:当前方案将图片转base64返回会增加约33%的传输体积,也可直接返回二进制图片流降低性能损耗

修正后代码

前端JS代码

// 按钮点击时触发
// 提前获取需要操作的DOM元素
const rs = document.getElementById('rsDiagram');
$.ajax({
    type: "GET",
    url: "/Home/RSView",
    data: { "orderNumber": $("#shopOrderNumber").val() },
    success: function (response) {
        rs.style.display = "block";
        // 修正选择器、移除多余的末尾引号
        $("#rsDiagram").attr("src", "data:image/png;base64," + response);
    },
    error: function (response) {
        alert(response.responseText);
    }
});

(可选)更高效的Controller实现(无需转base64)

如果直接返回图片流,前端不需要处理base64拼接,代码更简洁性能也更好:

public ActionResult RSView(string orderNumber)
{
    // 生成PNG并保存到wwwroot/images/的原有逻辑保留
    string outfile = Path.GetFullPath(Path.Combine(_hostingEnvironment.WebRootPath, "images", "RSView.png"));
    byte[] fileBytes = System.IO.File.ReadAllBytes(outfile);
    // 直接返回二进制图片流
    return File(fileBytes, "image/png");
}

对应前端JS可以简化为:

// 按钮点击时触发
const orderNumber = $("#shopOrderNumber").val();
$("#rsDiagram").attr("src", `/Home/RSView?orderNumber=${orderNumber}`).show();

View层原有代码无需修改。

内容的提问来源于stack exchange,提问作者Matthew Czajka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 23:57:02