R. StackUser R. StackUser - 9 months ago 50
ASP.NET (C#) Question

MVC - Store PDF in view model and embed in view?

I have a controller action that I can call and it returns a pdf file from a byte array. This works properly and I can view my document embedded on the page with this razor action:

<embed src="@Url.Action("Preview_PDF", "Doc", new { file_name = @Model })" width="100%" height="100%" type="application/pdf"></embed>


Is there a way to embed the file from a view model instead? for example

<embed src="@Model.file" width="100% " height="100%" type="application/pdf"></embed>


I'm using "return File" from my controller, which is not something that I can set into my model class, as File is a static type, it won't let me declare it as a variable.

How would I be able to embed the file on a page from a model? I can store the file as a byte array, but I do not know how to reconstruct it on the view.

Answer Source

It's possible, but you may get inconsistent results depending on the browser.

In your first example, you aren't actually embedding anything. You're emitting an <EMBED> tag with the location of the PDF; the browser is actually responsible for retrieving the PDF (in a separate HTTP request). So while there is a PDF embedded on the final page, it is not embedded in the HTTP response.

If you want to embed something so that the binary content appears inline in the HTML document, you'd follow this sort of syntax:

<EMBED Src="data:application/pdf;base64,[Based64-encoded string]">

So if @Model.file is a byte array containing the file, you can accomplish what you want by adding a new property to the model that returns the markup, like so:

class MyModel
{
    public string InlineMarkup
    {
        get
        {
            return String.Format("data:application/pdf;base64,{0}", Convert.ToBase64String(this.file));
        }
    }

...and in your view:

<embed src="@Model.InlineMarkup" width="100% " height="100%" type="application/pdf">

Note also that EMBED is a void element, so the </EMBED> tag is not needed and not strictly legal.

See also this question.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download