ASP.NET MVC控制器FileContent ActionResult通过AJAX调用

Ric*_*ick 13 asp.net ajax asp.net-mvc

设置:

控制器包含一个public ActionResult SaveFile()返回a 的方法FileContentResult.

什么有效:

视图包含一个表单,该表单提交此操作.结果是这个对话框:在此输入图像描述

什么行不通:

该视图包含一些javascript,用于对表单发布的同一个控制器操作进行AJAX调用.响应不是触发上述对话框,甚至是AJAX成功函数,而是触发AJAX错误函数,并XMLHttpRequest.responseText包含文件响应.

我需要做什么:

使用AJAX发出文件请求,最终得到与提交表单时相同的结果.如何让AJAX请求提供提交表单的对话框?

Nat*_*hot 16

这是我编写的一个简单示例.这是LukLed在调用SaveFile时所讨论的概念,但不通过ajax返回文件内容,而是重定向到下载.

这是视图代码:

<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>

<% } %>
Run Code Online (Sandbox Code Playgroud)

这是控制器代码:

[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();
    }
}
Run Code Online (Sandbox Code Playgroud)