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

ASP.NET MVC Core 6中View返回数据未正常渲染问题

问题根因

你的判断没错,问题就出在异步上传的逻辑上:Webcam.upload() 本质是发送AJAX异步请求,不会触发整页提交刷新。你后端UploadFile方法里返回的View("Index", "Home")渲染结果,只是作为HTTP响应体传回给了JS的上传回调函数,根本不会自动替换当前打开页面的DOM,所以你存在ViewData["Document"]里的doc数据虽然后端断点能查到,但完全没机会渲染到用户正在看的页面上。

可行解决方案

二选一即可,优先选第一种,交互体验更流畅:

方案1:后端返回JSON,前端动态渲染结果(推荐)

不用走整页刷新,直接在上传回调里拿后端返回的处理结果,手动插到页面对应位置。

  • 第一步修改后端C#方法,不要返回View,把处理好的doc对象序列化成JSON返回,顺便补上你漏写的文件保存逻辑:
public async Task<IActionResult> UploadFile()
{
    var files = HttpContext.Request.Form.Files;
    if (files == null || files.Count == 0)
    {
        return Json(new { success = false, message = "未选择文件" });
    }
    foreach (var uploadedFile in files)
    {
        if (uploadedFile.Length <= 0) continue;
        var fileName = uploadedFile.FileName;
        var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", fileName);
        // 补全文件保存逻辑,之前只拼了路径没实际写文件
        using (var stream = new FileStream(path, FileMode.Create))
        {
            await uploadedFile.CopyToAsync(stream);
        }
        HttpContext.Session.SetString("UploadedFile", fileName);
        byte[] imageBytes = ConvertToBytes(uploadedFile);
        Document doc = ProcessDocumentImage(imageBytes);
        // 直接返回处理结果
        return Json(new { success = true, data = doc });
    }
    return Json(new { success = false, message = "文档处理失败" });
}
  • 第二步修改前端JS的上传回调,解析返回的JSON数据后,按照你需要的格式把doc内容渲染到页面:
function CaptureSnapshot() {           
    Webcam.snap(function (data) {
        // 展示抓拍的快照
        document.getElementById('results').innerHTML = '<img src="' + data + '"/>';
        // 上传图片到后端
        Webcam.upload(data,
            '/Home/UploadFile',
            function (code, text) {
                Webcam.reset();
                const res = JSON.parse(text);
                if (!res.success) {
                    alert(res.message);
                    return;
                }
                const doc = res.data;
                // 按照你的页面需求拼接doc内容的HTML,示例如下,字段对应你的Document类属性改就行
                const docContentHtml = `
                <div class="document-result">
                    <h4>文档识别结果</h4>
                    <p>文档编号:${doc.Id}</p>
                    <p>文档类型:${doc.Type}</p>
                    <p>识别文本:${doc.RecognizeContent}</p>
                </div>
                `;
                // 把结果插到页面的结果容器里
                document.getElementById('results').insertAdjacentHTML('beforeend', docContentHtml);
            });
    });
}

方案2:上传完成后触发整页跳转,走传统MVC渲染

如果你不想写前端动态渲染逻辑,就想用Razor视图+ViewData/Model的方式渲染结果,就按下面改:

  • 后端修改:不要用ViewData存doc(重定向后ViewData会自动清空),把doc序列化后存Session,最后返回重定向而不是View:
// 把原来的 ViewData["Document"] = doc; 替换成下面这行
HttpContext.Session.SetString("ProcessedDoc", System.Text.Json.JsonSerializer.Serialize(doc));
// 把原来的 return View("Index", "Home"); 替换成
return RedirectToAction("Index");
  • 前端JS修改:在上传回调里加一行页面跳转代码,触发整页刷新:
Webcam.upload(data,
    '/Home/UploadFile',
    function (code, text) {
        Webcam.reset();
        // 跳转到首页,后端Index方法从Session里拿ProcessedDoc反序列化后传给视图渲染即可
        window.location.href = '/Home/Index';
    });

注意:这个方案会触发整页刷新,之前前端临时展示的抓拍快照会丢失,交互流畅度不如方案1。

内容的提问来源于stack exchange,提问作者Muhammad Usama Alam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 04:54:12