设置 :
Controller 包含一个方法 public ActionResult SaveFile()
返回 FileContentResult
.
什么有效 :
该 View 包含一个表单,该表单提交给此操作。结果是这个对话框:
什么不起作用 :
该 View 包含一些 javascript,用于对表单将发布的同一 Controller 操作执行 AJAX 调用。响应不是触发上述对话框,甚至不是 AJAX 成功函数,而是触发 AJAX 错误函数,以及 XMLHttpRequest.responseText
包含文件响应。
我需要做的:
使用 AJAX 请求文件,最终得到与提交表单时相同的结果。如何让 AJAX 请求提供提交表单显示的对话框?
最佳答案
这是我编造的一个快速示例。这就是 LukLed 在调用 SaveFile 但不通过 ajax 返回文件内容而是重定向到下载时所讨论的概念。
这是 View 代码:
<script src="../../Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
// hide form code here
// upload to server
$('#btnUpload').click(function() {
$.ajax({
type: 'POST',
dataType: 'json',
url: '<%= Url.Action("SaveFile", "Home") %>',
success: function(fileId) {
window.location = '<%= Url.Action("DownloadFile", "Home") %>?fileId=' + fileId;
},
error: function() {
alert('An error occurred uploading data.');
}
});
});
});
</script>
<% using (Html.BeginForm()) { %>
<div>Field 1: <%= Html.TextBox("field1") %></div>
<div>Field 2: <%= Html.TextBox("field2") %></div>
<div>Field 3: <%= Html.TextBox("field3") %></div>
<button id="btnUpload" type="button">Upload</button>
<% } %>
这是 Controller 代码:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public JsonResult SaveFile(string field1, string field2, string field3)
{
// save the data to the database or where ever
int savedFileId = 1;
// return the saved file id to the browser
return Json(savedFileId);
}
public FileContentResult DownloadFile(int fileId)
{
// load file content from db or file system
string fileContents = "field1,field2,field3";
// convert to byte array
// use a different encoding if needed
var encoding = new System.Text.ASCIIEncoding();
byte[] returnContent = encoding.GetBytes(fileContents);
return File(returnContent, "application/CSV", "test.csv");
}
public ActionResult About()
{
return View();
}
}
关于通过 AJAX 调用的 ASP.NET MVC Controller FileContent ActionResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2240869/