首页 > 解决方案 > 如何在等待 MVC 调用返回时为新选项卡显示加载图像或进度条?

问题描述

我在文件 generateReport.cshtml 中有一个 HTML 按钮,它打开一个新选项卡来显示报告:

<div>
   <a id="btnPreviewPDF" class="btn" href="#" title="Preview Report" target="_blank">Preview</a>
</div>

这将在 reportController.cs 中启动一个 MVC GET,它创建了要由呈现报告的 html 使用的模型:

[GET("PreviewPdf/{id:int}/{reportDate}")]
        public virtual ActionResult PreviewReport(int id, string reportDate)
        {            
            var helper = new ReportHelper(client);
            var model = helper.GenerateViewModelForPreviewReport(id, reportDate);

            return View(model);
        }

然后在viewReport.cshtml中使用上面的模型作为模型来展示数据,例如:

@model Reports.ReportHelper

<div class="sub-header-text primary-orange text-bold">
   Summary: @Model.ReportDate.ToString("MMMM") @Model.ReportDate.ToString("yyyy")
</div>

等待 PreviewReport 在 reportController.cs 的 GET 中返回可能需要 30 多秒才能运行,所以我想在通过单击“预览”按钮创建的新选项卡上显示加载图像/gif。由于此 GET 命令在 viewReport.cshtml 中的 HTML 代码之前运行,因此我无法找到一种方法来执行此操作。我想在该新选项卡上显示加载图像,并防止浏览器抛出认为页面没有响应的消息。任何人都可以帮助我或将我链接到一些信息吗?谢谢!

标签: javascriptc#htmlasp.net-mvc

解决方案


另一种方法是使用不显眼的 AJAX。您只需要从 Nuget 包管理器安装 Microsoft jQuery unobtrusive AJAX。

下载加载 GIF。

然后,在您看来,调用以下命令:

@{using (Ajax.BeginForm("Create", "ControllerName", null, new AjaxOptions()
     {
          HttpMethod = "POST",
          LoadingElementId = "divName",
          // ...
     }
}))
{
     // Html code goes here
     <div id="divName" class="col-md-12 text-center align-self-center" style="display:none;">
         <img src="~/Images/LoadingCircle.gif" alt="Loading..." />
     </div>
}

然后,此 div 将仅在加载时显示


推荐阅读