2011-04-17 102 views
0

我在頁面上調用ajax.action鏈接。這將顯示文檔的名稱。當我點擊文檔時,一個ajax請求被觸發到控制器,它將返回一個文件內容結果,並且我希望此文件在targetID div下在瀏覽器中內聯顯示。在ajax.action鏈接的部分頁面上顯示內聯文檔

代碼 - bytestream = fs.ToArray(); fs.Close(); Response.AppendHeader(「Content-Disposition」,String.Format(「inline; filename = {0}」,fileName)); return File(bytestream,「application/pdf」);

問題是,該文件顯示爲流,它沒有正確地顯示內容。

<legend>Document</legend> 
    <% if (Model.PresentDocument != null) 
     { %> 
    <li><%: Ajax.ActionLink(Model.PresentDocument, "GetDocumentPage", new RouteValueDictionary(new { controller = "Document", action = "GetDocumentPage", id = Model.PresDocId }), new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "Document" })%></li> 
    <%} %> 
    <div id="Document"> 
    </div> 

我需要爲這個div做任何特定的事情來顯示內聯pdf嗎?

回答

0

您無法使用AJAX下載文件。一種可能的方式實現這一目標是有一個正常的鏈接,點擊該鏈接時使用JavaScript動態生成一個iframe,指向的iframe源控制器動作:

<%= Html.ActionLink(
    Model.PresentDocument, 
    "GetDocumentPage", 
    "Document", 
    new { id = Model.PresDocId }, 
    new { id = "displayPdf" } 
) %> 

這是你可以AJAXify像這樣(使用jQuery):

$(function() { 
    $('#displayPdf').click(function() { 
     $('#Document').html(
      $('<iframe/>', { 
       src: this.href, 
       width: '300px', 
       height: '150px' 
      }) 
     ); 
     return false; 
    }); 
}); 

它假定您的控制器操作是通過訪問GET請求:

public ActionResult GetDocumentPage(string id) 
{ 
    byte[] pdf = ... 
    Response.AppendHeader("Content-Disposition", String.Format("inline; filename={0}", fileName)); 
    return File(pdf, "application/pdf"); 
} 
+0

哇。這就像一個魅力。謝謝 !。 ajax'targetID'可以映射到iframe嗎?基本上在我編寫的代碼中,它正確地將流下載到瀏覽器,但不顯示內容。就是想 ! – Sanjay 2011-04-17 15:49:01

+0

@Sanjay,不,這是不可能的。您需要使用'iframe'的'src'屬性將它指向一個將返回內容的服務器腳本。 – 2011-04-17 15:50:27

+0

謝謝!在您編寫的控制器代碼中,不需要返回FileContentResult? – Sanjay 2011-04-17 15:53:29

相關問題