Object or embed is not working in MVC

1k Views Asked by At

I am trying to show PDF into view using <embed> or <object> in MVC view page.

View.cshtml

<object data="@Server.MapPath(ViewBag.FileName)"  type="application/pdf" >
If you are unable to view file, you can download from
</object>

When I view page, I am getting PDF path correctly but PDF is not visible into page. enter image description here

My same code is working into simple HTML file.

Path: enter image description here

2

There are 2 best solutions below

3
ADyson On BEST ANSWER

As per the documentation at https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object, the data attribute of an <object> tag must be:

The address of the resource as a valid URL.

(the bold is mine, to make the point here).

In other words, you need to specify a URL pointing at the PDF, not a file path. The browser has no access to the server's disk, so it cannot read directly from it. All it can do is make a HTTP request to a URL to get the document.

So it might be something like this:

<object data="documents/@ViewBag.FileName"  type="application/pdf" >

but of course exactly what you use depends on where you place the document, and exactly what you have put into ViewBag.Filename already.

Note that the App_Data folder in an MVC application is not accessible from the web (and it's not desirable to make it accessible, since it contains things like database files), so you'll have to place the PDF somewhere else more suitable.

6
Andreas Gustafsson On

Can you not do a Method that returns a FileContentResult that reads the file and just display the content on the frontend?

And add a Click here to download to be able to download it if that is necessary.

Cheeres!