在ASP.net MVC4中导出没有页面导航的文件button

我正在研究一个ASP.net MVC4 Web应用程序,并希望支持从/到Excel的导入/导出function。 我写了代码(或动作)导出为Excel,但在编写导入/导出button时遇到麻烦。

具体而言,我只想要只调用导出操作的button,并在当前页面上不做任何事情。

  1. 项目详细信息页面(查看):在项目的详细信息,我有这些button 在这里输入图像说明
  2. ExcelController有ExportToFile方法
  3. 我尝试使用Ajax.ActionLink和Html.ActionLink,但在两种情况下,页面导航到
     本地主机:52725 / Excel中/ ExportToFile PID = 41? 

项目详情页面:

<div class="btn-group" id="footerButtons"> @Html.ActionLink("Edit Project", "Edit", new { id = Model.ProjectId }, new { @class = "btn btn-primary " }) @using(Html.BeginForm("ExportToFile", "Excel")) { <button class="btn" title="Export to Excel" type="submit">Export (Excel)</button> } @Ajax.ActionLink("Export (Excel)", "ExportToFile", "Excel", new { pid = Model.ProjectId }, new AjaxOptions { HttpMethod = "Post", UpdateTargetId="footerButtons", }, new { @class = "btn" }) <!-- Back to results button--> </div> 

Excel控制器

 public class ExcelController : ControllerBase { public void ExportToFile(int pid = 0) { // Code to create and write to excel file // Main point is it returns nothing which I speculate to be wrong. } } 

你想要的方法签名看起来像

 public FileContentResult ExportToFile(int pid = 0) 

并使用Controller.File方法输出

就像是

 return File(fileBytes, "application/vnd.ms-excel", unique generated file name); 

从控制器返回并最终发送数据到浏览器

作为一个简单的testing

 return this.File(new System.Text.UTF8Encoding().GetBytes("my plain text content"), "text/plain", "my_file.txt"); 

应该返回一个纯文本文件。