点击文本在模态框(modal)中展示PDF的代码修改方案咨询
实现点击PDF链接在模态框中预览的修改方案
问题背景
当前页面点击PDF文档名称时,会调用Controller并在新页面打开PDF,需要改为在模态框中展示PDF。
现有代码
View代码
<a href="@Url.Action("GetPDF", "Home", new { Model.Id })"> Document Name: @Model.documentType </a>
Controller代码
public async Task<ActionResult> GetPDF(Guid id) { var vm = new ViewModels.Home.AttachmentViewModel(); var result = vm.GetServiceAttachment(id); //Function to get the file information from DB . byte[] file; foreach (var attachment in result) { file = attachment.File; byte[] byteArray = file; return new FileContentResult(byteArray, "application/pdf"); } return null; }
修改步骤
1. 修改View层代码
需要添加模态框结构、调整链接的点击逻辑,并编写JS处理PDF加载:
调整链接标签
将原a标签的跳转行为改为触发自定义函数:
<a href="javascript:void(0)" onclick="openPdfModal('@Url.Action("GetPDF", "Home", new { id = Model.Id })')"> Document Name: @Model.documentType </a>
添加模态框HTML结构
在页面合适位置添加Bootstrap风格的模态框(如果项目未引入Bootstrap,需先引入相关CSS和JS):
<!-- PDF预览模态框 --> <div class="modal fade" id="pdfModal" tabindex="-1" role="dialog" aria-labelledby="pdfModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="pdfModalLabel">PDF文档预览</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <iframe id="pdfViewer" width="100%" height="600px" frameborder="0"></iframe> </div> </div> </div> </div>
添加JavaScript逻辑
在页面底部或脚本文件中添加处理PDF加载的函数:
function openPdfModal(pdfUrl) { // 通过fetch获取PDF的二进制数据 fetch(pdfUrl) .then(response => { if (!response.ok) throw new Error('请求失败'); return response.blob(); }) .then(blob => { // 生成Blob URL用于iframe加载 const blobUrl = URL.createObjectURL(blob); // 给iframe设置源并打开模态框 document.getElementById('pdfViewer').src = blobUrl; $('#pdfModal').modal('show'); }) .catch(error => { console.error('加载PDF出错:', error); alert('无法加载PDF文档,请稍后重试'); }); }
2. 优化Controller层代码
原Controller逻辑存在冗余(循环内直接return,只会取第一个附件),同时添加空值判断增强健壮性:
public async Task<ActionResult> GetPDF(Guid id) { var vm = new ViewModels.Home.AttachmentViewModel(); var result = vm.GetServiceAttachment(id); // 获取第一个附件(原逻辑只会返回第一个) var attachment = result.FirstOrDefault(); if (attachment == null) { // 附件不存在时返回404 return NotFound(); } return new FileContentResult(attachment.File, "application/pdf"); }
说明
- 若项目未使用Bootstrap,可替换为自定义模态框逻辑,核心是通过Blob URL在iframe中加载PDF
- 模态框的尺寸、样式可根据需求自行调整
- 若浏览器不支持直接在iframe中预览PDF,可考虑引入PDF.js等第三方库增强兼容性
内容的提问来源于stack exchange,提问作者Michaelweston
相关产品推荐
相关产品推荐

