在我的 Controller 中,我有以下操作来创建 PDF
public async Task<IActionResult> ExportMailingLabel(int CustomerID, int ProductID)
{
var mailingLabel = await NoticeService.CreateMailingLabel(CustomerID, ProductID);
return File(mailingLabel.NoticeContents, "application/pdf", "MailingLabel.pdf");
}
在我看来,我有以下链接,
<a asp-action="ExportMailingLabel" asp-controller="Product" asp-area="Product" asp-route-CustomerID="@Model.CustomerID" asp-route-ProductID="@Model.ProductID" class="btn btn-primary"><i class="fa fa-receipt"></i> View Mailing Label</a>
单击在新选项卡中打开 PDF 而不是显示“打开”对话框时,我需要帮助。
我尝试了target="_blank"
,但我似乎打开了一个新选项卡,但仍然显示打开的对话框
最佳答案
_target="blank"
是一个简单的 HTML 标记,我认为它可以按预期在所有浏览器中工作。您可以将其与静态或动态文件名一起使用,如下所示。
静态文件名用法
Controller .cs
public async Task<IActionResult> ExportMailingLabel(int CustomerID, int ProductID) {
var mailingLabel = await NoticeService.CreateMailingLabel(CustomerID, ProductID);
return File(mailingLabel.NoticeContents, "application/pdf");//we don't send 3.parameter yet
}
查看.cshtml
<a asp-action="ExportMailingLabel"
asp-controller="Product"
asp-route-CustomerID="@Model.CustomerID"
asp-route-ProductID="@Model.ProductID"
asp-route-FileName="MailingLabel.pdf" class="btn btn-primary" id="btnOpenDocument">
<i class="fa fa-receipt"></i> View Mailing Label
</a>
@section Scripts
{
<script>
//We are opening the file with js instead of action when click to the button
$('#btnOpenDocument').click(function (e) {
e.preventDefault();
window.open('@Url.Action("ExportMailingLabel"
,"Product"
,new {customerId=selectedCustomerId
,productId=selectedProductId
,fileName="MailingLabel.pdf" })'
,"_blank");
});
</script>
}
动态文件名用法
Controller .cs
//We are adding a new route to action for file name
[HttpGet("[controller]/[action]/{customerId}/{productId}/{fileName}")]
public async Task<IActionResult> ExportMailingLabel(int CustomerID, int ProductID) {
var mailingLabel = await NoticeService.CreateMailingLabel(CustomerID, ProductID);
return File(mailingLabel.NoticeContents, "application/pdf", $"{CustomerID}_{ProductID}.pdf");
}
查看.cshtml
<a asp-action="ExportMailingLabel"
asp-controller="Product"
asp-route-CustomerID="@Model.CustomerID"
asp-route-ProductID="@Model.ProductID"
asp-route-FileName="@(Model.CustomerID)_@(Model.ProductID).pdf" class="btn btn-primary" id="btnOpenDocument">
<i class="fa fa-receipt"></i> View Mailing Label
</a>
@section Scripts
{
<script>
//We are opening the file with js instead of action when click to the button
$('#btnOpenDocument').click(function (e) {
e.preventDefault();
window.open('@Url.Action("ExportMailingLabel"
,"Product"
,new {customerId=selectedCustomerId
,productId=selectedProductId
,fileName=selectedCustomerId+"_"+selectedProductId+".pdf" })'
,"_blank");
});
</script>
}
关于asp.net-core - ASP.NET Core 如何在新选项卡中打开 PDF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62805338/