以下示例中的第一個運行良好。第二個 istn 作業,pdf 保存到資料庫但 Onpost 方法不起作用
1.(作業示例)我正在這樣做_taget="blank并呼叫一個空的 Razor-Page。代碼看起來像這樣。
HTML
<a class="btn btn-outline-dark" data-toggleToolTip="tooltip" data-placement="top"
title="Anzeigen" asp-page="/Invoices/DisplayInvoiceAsPdf" asp-route-invoiceId="@item.Nr" target="_blank">
<i class="fa-solid fa-download"></i>
</a>
空 Razor-Page 背后的代碼:
public class DisplayInvoiceAsPdfModel : PageModel
{
private readonly IDataRepository _DataRepository;
public DisplayInvoiceAsPdfModel(IDataRepository DataRepository)
{
_DataRepository = DataRepository;
}
public Kopfdaten Kopfdaten { get; set; }
public async Task<IActionResult> OnGetAsync(int id)
{
Kopfdaten = await _DataRepository.GetDataById(id);
if(Kopfdaten.Pdf == null)
{
return NotFound();
}
return File(Kopfdaten.Pdf, "application/pdf");
}
}
當我單擊按鈕時,Pdf 將在新選項卡中打開(在 Google Chrome 中)。
2.(不作業示例):我在 OnPostmMethod 中創建預覽 Pdf,在創建 Pdf 并將其存盤到我的資料庫后應該打開 PDf。我想用 await OnPostPDf(id)
if (y == "OK")
{
//Ok=> Open Pdf in new Tab
await OnPostPDF(id);
if (testBool == true)
{
//Refresh page ,error
return RedirectToPage("Invoice", new { Id = adrId});
}
else
{
//Post
return RedirectToPage("/Index");
}
}
OnpostPdf 看起來像這樣:
public async Task<IActionResult> OnPostPDF(int id)
{
Kopfdaten kopfdaten = new Kopfdaten();
kopfdaten = await _DataRepository.DataById(id);
if (kopfdaten.Pdf == null)
{
return NotFound();
}
return File(kopfdaten.Pdf, "application/pdf");
}
按 ID 獲取資料
public async Task<Kopfdaten> GetDataById(int id)
{
try
{
return await _Context.Kopfdaten.FindAsync(id);
}
catch (Exception ex)
{
throw new Exception($"Couldn't retrieve entities: {ex.Message}");
}
}
Kopfdaten 型號:
public partial class Kopfdaten
{
public int Id { get; set; }
public int InVoiceNumber { get; set; }
public string Text { get; set; }
public int AdressId{ get; set; }
public byte[] Pdf { get; set; }
}
uj5u.com熱心網友回復:
“如何在 Post Method 中打開 PDF(在新視窗中,或下載)”
所以有3種方法來處理這種情況。
方式:1當您的應用程式檔案夾中有現有的PDF檔案時
在這種情況下,假設您PDF file的應用程式檔案夾中有如下所示:

解決方案:
public ActionResult DisplayPDFFromExistingFile()
{
string physicalPath = "wwwroot/KironGitHub.pdf";
byte[] pdfBytes = System.IO.File.ReadAllBytes(physicalPath);
MemoryStream ms = new MemoryStream(pdfBytes);
return new FileStreamResult(ms, "application/pdf");
}
輸出:

方式:2 當您想從資料庫模型在瀏覽器上顯示 PDF 時
解決方案:
public ActionResult DisplayPdfOnBrowserFromDatabaseList()
{
var data = _context.Members.ToList();
var pdf = data.ToPdf();
MemoryStream ms = new MemoryStream(pdf);
return new FileStreamResult(ms, "application/pdf");
}
注意:要處理這種情況,您需要使用
方式:3 當您想在瀏覽器上從資料庫模型或現有檔案中下載 PDF 時
解決方案:
public ActionResult DownloadPDFOnBrowser()
{
var data = _context.Members.ToList();
var byteArray = data.ToPdf();
MemoryStream stream = new MemoryStream(byteArray);
string mimeType = "application/pdf";
return new FileStreamResult(stream, mimeType)
{
FileDownloadName = "DatabaseListToPdf.pdf"
};
}
注意:如上所述,我們需要using ArrayToPdf;在頂部添加。要處理這種情況,您需要使用
您也可以查看
這些是我們如何處理您遇到的問題的用例場景。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/489398.html
