_target="blank"
is a simple HTML tag once for all and I think that it works in all browsers as expected. You can use it with a static or dynamic file name as follows.
STATIC FILE NAME USAGE
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
}
View.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>
}
DYNAMIC FILE NAME USAGE
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");
}
View.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>
}
FileContentResult Class