Iframe shows ActionMethod name while loading PDF file in ASP MVC

你离开我真会死。 提交于 2019-12-12 04:17:21

问题


i am using iframe tag in order to call ActionMethod that returns FileResult to display PDF file. The issue is after it loads PDF document instead of showing pdf file name, it shows ActionMethod name on the top of the PDF file name in Chrome.

Razor Code:

<iframe src="@Url.Action("GetAgreementToReview", "Employee")" style="zoom: 0.60; -ms-zoom: 1; width: 100%;" width="99.6%" height="420" frameborder="0" id="agreementPdf"></iframe>

CS Code:

public ActionResult GetAgreementToReview()
{
  Response.AddHeader("Content-Disposition", "inline; filename=Master-Agreement.pdf");    
  return File("~/Content/Master-Agreement.pdf", "application/pdf");
}

Image: As you can see in the screenshot, it shows 'GetAgreementToReview' i.e. ActionMethod name instead of 'Master-Agreement.pdf'.

Does anyone know how to fix this issue? Thanks.

Sanjeev


回答1:


I had a similar problem and found a solution after exploring almost everything the web has to offer.

You must use a custom route for your action and you must send the filename from UI into the URL itself. (Other parameters won't be affected)

//add a route property
[Route("ControllerName/GetAgreementToReview/{fileName?}")]
public ActionResult GetAgreementToReview(string fileName, int exampleParameter)
{
     byte[] fileData = null; //whatever data you have or a file loaded from disk

     int a = exampleParameter; // should not be affected

     string resultFileName = string.format("{0}.pdf", fileName); // you can modify this to your desire

     Response.AppendHeader("Content-Disposition", "inline; filename=" + resultFileName);
     return File(fileData, "application/pdf"); //or use another mime type
}

And on client-side, you can use whatever system to reach the URL.

It's a bit hacky, but it works.

If you have an Iframe on HTML to display the PDF (the issue I had), it could look like this:

<iframe src='/ControllerName/GetAgreementToReview/my file?exampleParameter=5' />

And this way you have a dynamic way of manipulate the filename shown by the IFRAME that only uses the last part of an URL for its name shown on the web page (quite annoying). The downloaded filename will have its name given from server-side Content-disposition.

Hope it helps !




回答2:


please try this code :

return File("~/Content/Master-Agreement.pdf", "application/pdf", "filename.pdf");

Other Helper Link : Stream file using ASP.NET MVC FileContentResult in a browser with a name?



来源:https://stackoverflow.com/questions/34658690/iframe-shows-actionmethod-name-while-loading-pdf-file-in-asp-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!