从 this question I previously asked 开始我想知道 - 在我的 Controller 操作返回文件并写入响应后,是否也可以显示 Javscript 警报?
请注意这个项目是MVC 1.0
这是我要在文件下载之前执行一些 Javascipt 的 ActionReult:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SomeImporter(HttpPostedFileBase attachment, FormCollection formCollection, string submitButton, string fileName)
{
if (submitButton.Equals("Import"))
{
byte[] fileBytes = ImportClaimData(fileName, new CompanyExcelColumnData());
if (fileBytes != null)
{
//This method stores the string in a message queue which is stored in the
//session and rendered from within a UserControl. The Javascript alert
//is then shown subsequently.
UserMessageUtil.Info("Data imported successfully.", Session);
//The file downloads but no Javascript alert is shown from the line above.
return File(
fileBytes,
"application/ms-excel",
string.Format("Import {0}.xls", DateTime.Now.ToString("yyyyMMdd HHmm")));
}
return View();
}
throw new ArgumentException("Value not valid", "submitButton");
}
用于处理用户控件内部队列的 HTML Helper 方法:
public static string UserMessage(this HtmlHelper helper, HttpSessionStateBase session)
{
MessageQueue queue = UserMessageUtil.GetMessageQueue(session);
Message message = queue.Next;
String script = null;
if (message != null)
{
do
{
string messageStr = message.Text;
....
script += @"alert('" + messageStr + "');";
}
while ((message = queue.Next) != null);
return script;
}
return null;
}
基本上,文件下载但 Javascript 警报不显示。 UserMessageUtil.Info()
用于项目的其他部分并按预期工作,在执行时显示警报。
最佳答案
如果我理解正确,您希望在文件准备好下载后执行一些客户端 javascript 吗?
我有过类似的需求,尽管它是 Java EE,但技术问题仍然存在。在这里看看这个精彩的技巧 http://geekswithblogs.net/GruffCode/archive/2010/10/28/detecting-the-file-download-dialog-in-the-browser.aspx正如此答案中的特色 Detect when browser receives file download
基本上,您希望从您的操作中设置一个 cookie,该 cookie 将随服务器响应一起返回,并在客户端进行一些 javascript 轮询以了解该 cookie 是否存在。一旦服务器响应并向客户端显示文件下载对话框,就会检测到 cookie 并执行您的脚本。执行脚本后,您可以销毁 cookie。
关于c# - 同时执行 Javascript 和 Controller ActionResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14747746/