首页 文章

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

提问于
浏览
13

The setup

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

What works

视图包含一个表单,该表单提交此操作 . 结果是此对话框:
enter image description here

What doesn't work

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

What I need to do:

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

1 回答

  • 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>
    
    <% } %>
    

    这是控制器代码:

    [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();
        }
    }
    

相关问题