Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC open pdf file in new window

I have a MVC application. I need to open the pdf file when user clicks the open button on the page. The filepath where the pdf is stored is read from the database and it is a file on c:. How do I open it in my html code? I have this code:

<a href="@Model.CertificatePath" target="_blank" class="button3">Open</a>

but this doesn't open my file. What do I have to do? I need to specify somewhere that it is a pdf??

like image 961
Tulips Avatar asked Jun 19 '12 12:06

Tulips


People also ask

How do I open a PDF in a new tab or window instead of downloading it using C# and ASP NET MVC?

click(function (e) { // if using type="submit", this is mandatory e. preventDefault(); window. open('@Url. Action("PdfInvoice", "ControllerName", new { customerOrderselectedId = selectedId })', '_blank'); });


2 Answers

You will need to provide a path to an action that will receive a filename, resolve the full path, and then stream the file on disk from the server to the client. Clients out in the web, thankfully, cannot read files directly off your server's file system (unless... are you suggesting @Model.CertificatePath is the path to the file on the remote user's machine?).

public ActionResult Download(string fileName)
{
   string path = Path.Combine(@"C:\path\to\files", fileName);

   return File(path, "application/pdf");

}

Update

If @Model.CertificatePath is the location on the client's actual machine, try:

 <a href="file://@Model.CertificatePath" target="_blank" class="button3">Open</a>

Note that some browsers may have security settings disallowing you from opening local files.

like image 138
moribvndvs Avatar answered Sep 21 '22 12:09

moribvndvs


Well if your getting the path value and the value is in @Model.CertificatePath

this wiil not work

<a href="@Model.CertificatePath" target="_blank" class="button3">Open</a>

You will need to add this

<a href="@Url.Content(Model.CertificatePath)" target="_blank" class="button3">Open</a>

and make sure you path is relative by adding this ~ for example if your path is /Content/pdfs/CertificatePath.pdf

it would need to look like

~/Content/pdfs/CertificatePath.pdf

This should be the simplest way to make it work. Hope this helps.

like image 30
wilaponce Avatar answered Sep 18 '22 12:09

wilaponce