开发者

Show pdf in the browser in ASP.NET MVC

开发者 https://www.devze.com 2023-01-02 16:10 出处:网络
I have a tab on my page, when i click on this tab, i need to show a pdf file on page(browser). For this i am writing function on control like this

I have a tab on my page, when i click on this tab, i need to show a pdf file on page(browser). For this i am writing function on control like this

public ActionResult PricedPdf(string projID,string file开发者_运维问答Name)
{
    byte[] bArr = new byte[] { };
    bArr = getdata();    
    return File(bArr, System.Net.Mime.MediaTypeNames.Application.Pdf, fileName+".pdf");
}

Now my problem is when i render this, page only show some unreadable data not pdf.

May be the problem is due to jquery tab, I am using Jquery tab

I used this in place of File, but still showing same problem

public ActionResult PricedPdf(string projID, string fileName)
{
    byte[] bArr = new byte[] { };
    bArr = getdata();
    Response.AddHeader("Content-disposition", "inline; filename=\"" + fileName + "\"");
    Response.ContentType = "application/" + System.IO.Path.GetExtension(fileName).Replace(".", "");    
    Response.BinaryWrite(bArr);
    Response.Flush();
}


How are you calling this PricedPdf action? If you are calling it with AJAX then forget about it. You cannot return PDF from an AJAX call or more precisely you can but there's not much you can do with it. So create a normal html link pointing to this action:

<%= Html.ActionLink("show pdf", "PricedPdf") %>

Once you click on the resulting anchor the browser will be redirected to a page that will open the resulting PDF using the appropriate plugin installed on your system (provided there's any). If you don't want opening the PDF in the current browser window you could add the target="_blank" attribute to the anchor.

Finally if you want to open the PDF only inside some portion of the page you could embed it into the markup.

So basically you would have a controller action that will return a partial HTML containing the PDF inclusion:

public ActionResult SomePartial()
{
    return PartialView();
}

And the partial might look like this:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<object type="application/pdf" data="<%= Url.Action("PricedPdf") %>" width="500" height="650">
    Click <%= Html.ActionLink("here", "PricedPdf") %> to view the file
</object>

And in you would use this action in your AJAX call.

0

精彩评论

暂无评论...
验证码 换一张
取 消