ASP.NET Core使用ViewAsPdf导出PDF时ViewBag值不显示问题咨询
问题原因
- 核心原因是
Rotativa.AspNetCore的ViewAsPdf实例不会自动继承当前控制器上下文的ViewBag/ViewData数据,直接返回新建的ViewAsPdf对象时,视图渲染时拿到的是空的ViewData集合,而ViewBag本质是ViewData的动态包装器,因此视图中读取的ViewBag内容全部为空。 - 额外可排查点:可先在控制器方法入口打断点,确认请求传入的
UserName和ActivityName参数是否正常接收,若参数本身为空,后续赋值的ViewBag也会是空值。 - 视图代码未使用
ViewBag.ActivityName,就算ViewBag传值成功,活动名称也不会在PDF中展示。
解决方法
方案1:手动传入ViewData(适配你当前用ViewBag的写法)
修改控制器代码,给ViewAsPdf的ViewData属性赋值为当前控制器的ViewData即可,修改后的代码如下:
public IActionResult PrintCertification(String UserName , String ActivityName ) { ViewBag.UserName = UserName; ViewBag.ActivityName = ActivityName; return new ViewAsPdf("PrintCertification") { PageOrientation = Rotativa.AspNetCore.Options.Orientation.Landscape, // 手动传入当前控制器的ViewData,即可把ViewBag内容带到视图中 ViewData = ViewData }; }
同时修改视图代码,把需要动态展示活动名的位置替换成@ViewBag.ActivityName,示例如下:
<h3 id="content"> For his valuable participation as ( a leader/an organizer) in the (campaign/ activity/ course) of <br>@ViewBag.ActivityName, that aims to ( aim of the activity).<br> Targeting (target audience).<br> Held in ( place), On (Date). </h3>
方案2:改用强类型ViewModel传参(更规范,避免动态类型拼写错误)
- 先定义视图模型类
public class CertificationViewModel { public string UserName { get; set; } public string ActivityName { get; set; } // 其他需要动态填充的字段均可在此定义 }
- 修改控制器代码,直接把模型传给
ViewAsPdf
public IActionResult PrintCertification(string UserName , string ActivityName ) { var model = new CertificationViewModel { UserName = UserName, ActivityName = ActivityName }; return new ViewAsPdf("PrintCertification", model) { PageOrientation = Rotativa.AspNetCore.Options.Orientation.Landscape }; }
- 修改视图代码,声明模型后取值
@model CertificationViewModel <html> <head> <h1 id="CA" style="align-content:center">Certificate of Apperciation</h1> </head> <body class="bg" style="background-image: url(https://localhost:44387/Screenshot.png); "> <h3 id="TC">The College of Medicine at King Faisal University would like to thank</h3> <h1 id="name">@Model.UserName</h1> <h3 id="content"> For his valuable participation as ( a leader/an organizer) in the (campaign/ activity/ course) of <br>@Model.ActivityName, that aims to ( aim of the activity).<br> Targeting (target audience).<br> Held in ( place), On (Date). </h3> <h4 id="Dr">Dr. Naif Mohammed Alhmam</h4> <h4 id="OS">Official Seal</h4> <h4 id="VD">Vice-dean for development <br>and community partnership</h4> </body> </html>
额外优化提示
你当前视图中背景图用的是localhost本地地址,部署到生产环境后会无法加载,建议将图片转为base64编码嵌入视图,或者替换为服务器的公网绝对地址。
内容的提问来源于stack exchange,提问作者abdulelah alasfour
相关产品推荐
相关产品推荐

