2009-12-10 106 views
4

我有以下問題: 我有一個MVC應用程序,在某些控制器的某些動作中,我正在生成PDF文件,該文件正在服務器上的特定路徑上生成。該操作在視圖的操作鏈接上被調用,當用戶單擊該鏈接時,該操作生成該PDF,一切都很好,直到這裏。 我想要的網頁,以顯示我的生成PDF文件,該文件說的對話框:MVC打開pdf文件

打開 - 保存 - 取消(該tipical文件對話框,當你點擊一個文件)

但無需刷新頁面,只顯示用戶點擊鏈接時的對話框。

我該怎麼做?該行動應該返回到該視圖? 謝謝。

回答

3

要提供打開 - 保存 - 取消對話框,您需要設置適當的響應標頭,並且@RichardOD說,返回FilePathResult或FileStreamResult。

HttpContext.Response.AddHeader("content-disposition", "attachment; 
           filename=form.pdf"); 

return new FileStreamResult(fileStream, "application/pdf"); 
+0

'FileStreamResult'和'FilePathResult'都有一個屬性'FileDownloadName',您應該使用它來代替m每次設置''content-disposition''標頭。 – 2011-06-24 19:44:37

0

嘗試這樣的事情

public class PdfResult : ActionResult 
    { 
     //private members 
     public PdfResult(/*prams you need to generate that pdf*/) 
     public override void ExecuteResult(ControllerContext context) 
     { 
      //create the pdf in a byte array then drop it into the response 
      context.HttpContext.Response.Clear(); 
      context.HttpContext.Response.ContentType = "application/pdf"; 
      context.HttpContext.Response.AddHeader("content-disposition", "attachment;filename=xxx.pdf"); 
      context.HttpContext.Response.OutputStream.Write(pdfBytes.ToArray(), 0, pdfBytes.ToArray().Length); 
      context.HttpContext.Response.End(); 
     } 
    } 

然後你剛剛返回PdfResult

提示:我有一個泛型類的這樣做的,它是這樣的,我使用NFop

public PdfResult(IQueryable source, Dictionary<string,int> columns, Type type) 
    { 
     Source = source; 
     Columns = columns; 
     SourceType = type; 
    }