ASP.NET MVC Controller FileContent ActionResult通过AJAX调用

前端之家收集整理的这篇文章主要介绍了ASP.NET MVC Controller FileContent ActionResult通过AJAX调用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
设置:

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

什么工作:

该视图包含一个表单,它提交到此操作.结果是这个对话框:

什么不行:

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

我需要做什么:

使用AJAX对文件进行请求,结果与提交表单时的结果相同.如何使AJAX请求提供提交表单的对话框?

解决方法

这是一个快速的例子.这是LukLed正在调用SaveFile的概念,但是不要通过ajax返回文件内容,而是重定向到下载.

这是查看代码

@H_404_22@<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> <% } %>

这是控制器代码

@H_404_22@[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(); } }
原文链接:https://www.f2er.com/aspnet/250393.html

猜你在找的asp.Net相关文章