如何在新的标签页或窗口中打开PDF文件,而不是使用C#和ASP.NET MVC下载PDF文件?

时间:2019-03-05 05:06:52

标签: c# asp.net-mvc pdf

我有发票屏幕,并且在此屏幕上有可用的订单数量,因此当我们创建发票时,我们需要填写一张表格,因此我想解决的方法是当我提交此发票表格或单击此提交按钮时,pdf在新标签页中打开。我想向您澄清,我们不会将此pdf保存在任何地方。

<div class="modal-footer custom-no-top-border">
      <input type="submit" class="btn btn-primary" id="createdata" value="@T("Admin.Common.Create")" />
</div>

当我单击此按钮时,应该在新选项卡中打开pdf。

这是pdf代码

 [HttpPost]
 public virtual ActionResult PdfInvoice(int customerOrderselectedId)
 {
        var customerOrder = _customerOrderService.GetCustomerOrderById(customerOrderselectedId);

        var customerOrders = new List<DD_CustomerOrder>();

        customerOrders.Add(customerOrder);
        byte[] bytes;

        using (var stream = new MemoryStream())
        {
            _customerOrderPdfService.PrintInvoicePdf(stream, customerOrders);
            bytes = stream.ToArray();
        }

        return File(bytes, MimeTypes.ApplicationPdf, string.Format("order_{0}.pdf", customerOrder.Id));
    }

当我单击按钮时,此代码将下载pdf。

谢谢!!

1 个答案:

答案 0 :(得分:2)

最重要的是Controller.File()[HttpGet]一起使用,因此您应该执行以下步骤:

1)将HTTP方法类型从[HttpPost]更改为[HttpGet],并在不指定return File()参数的情况下设置fileDownloadName(使用Controller.File()的重载,该参数接受2个参数)

[HttpGet]
public virtual ActionResult PdfInvoice(int customerOrderselectedId)
{
    var customerOrder = _customerOrderService.GetCustomerOrderById(customerOrderselectedId);

    var customerOrders = new List<DD_CustomerOrder>();

    customerOrders.Add(customerOrder);
    byte[] bytes;
    using (var stream = new MemoryStream())
    {
        _customerOrderPdfService.PrintInvoicePdf(stream, customerOrders);
        bytes = stream.ToArray();
    }

    // use 2 parameters
    return File(bytes, MimeTypes.ApplicationPdf);
}

2)处理该按钮的click事件(最好使用<input type="button" .../>)并使用_blank选项,或者将锚标签(<a>)与{{1} }属性:

target='_blank'

此处未使用$('#createdata').click(function (e) { // if using type="submit", this is mandatory e.preventDefault(); window.open('@Url.Action("PdfInvoice", "ControllerName", new { customerOrderselectedId = selectedId })', '_blank'); }); 参数的原因是,在提供文件名时,该参数设置了fileDownloadName,否则,如果您忽略它或使用Content-Disposition: attachment值,则{{ 1}}会自动设置。

请注意,由于您使用的是null,因此请勿在{{1​​}}之前使用Content-Disposition: inline来设置FileResult,因为这样做会发送多个{{1} }标头,导致浏览器无法显示文件:

Content-Disposition

相关问题:

How To Open PDF File In New Tab In MVC Using C#

ASP.NET MVC: How can I get the browser to open and display a PDF instead of displaying a download prompt?

Stream file using ASP.NET MVC FileContentResult in a browser with a name?