Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

opening a pdf file in modal possible?

i was thinking of opening a pdf file in modal . current using

@Html.ActionLink("open file", "Download")

open another windows. i want it to populate it to a div so that i can view in in modal or overlay.

i am ok with jquery solution as well as currently my jquery return me some bytes character.

function openfile() {
    $.ajax({
        url: '@Url.Action("Download", "mycontroller")',
        type: "POST",
        dataType: "application/pdf",
        success: function (data) {
            $('#showpdf').html(data);
        },
        error: function (err) {
           alert(err)
        }
    });
}

Action in the controller:

public ActionResult Download()
{
    string path = HttpContext.Server.MapPath("/pdf/service_reports/SR26175.pdf");
    return File(path, "application/pdf");
}
like image 313
MVC newbie Avatar asked Sep 01 '25 17:09

MVC newbie


2 Answers

Another way to do this is pass pdf path from json request and then use object inside the modal div:

<object id="myPdf" type="application/pdf" data="path/file.pdf"></object>

function openfile() {
    $.ajax({
        url: '@Url.Action("Download", "mycontroller")',
        type: "POST",
        dataType: "application/json",
        success: function (data) {
            $('#showpdf').html('<object id="myPdf" type="application/pdf" data="' + data.path +'"></object>');
        },
        error: function (err) {
            alert(err)
        }
    });
}

public ActionResult Download()
{
    string path = HttpContext.Server.MapPath("/pdf/service_reports/SR26175.pdf");
    return Json(new {path = path});
}

EDIT: For better user experience on different browsers that maybe doesn't support object tag, we could use object with embed tag as a fallback:

<object data="/path/file.pdf" type="application/pdf" width="700px" height="700px">
    <embed src="/path/file.pdf">
        This browser does not support PDFs. Please download the PDF to view it: <a href="/path/file.pdf">Download PDF</a>.</p>
    </embed>
</object> 
like image 147
Alexander V. Avatar answered Sep 04 '25 08:09

Alexander V.


Assuming you have a controller named home. You can use an iframe like this

<div id='yourModel'>
   <iframe src="/Home/Download"></iframe>
</div>

and use jQuery to show / hide the div.

like image 21
Muhammad Bashir Avatar answered Sep 04 '25 07:09

Muhammad Bashir