2009-12-10 99 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; 
    }