[英]How can I return javascript from a controller actionresult using ContentResult?
我想知道當文件夾中未創建通常生成的文件時,如何返回 javascript 警報。 運行 else 語句時,它會返回瀏覽器選項卡頂部的文字文本,而不是我正在尋找的警報。 它看起來像這樣:
代碼:
public ActionResult DownloadFile(string path, string fileName)
{
if (System.IO.File.Exists(path))
{
byte[] fileBytes = System.IO.File.ReadAllBytes(path);
return File(fileBytes, "application/force-download", fileName);
}
else
{
return Content("<script language='javascript' type='text/javascript'>alert('No data was found to create a CSV file!');</script>");
}
}
首先你可以使用方法public virtual ContentResult Content(string content, string contentType);
而不是public virtual ContentResult Content(string content);
Controller:
public ActionResult DownloadFile()
{
return Content("alert('No data was found to create a CSV file!');", "application/javascript");
}
另外,你也可以寫一個具有參數構造函數並擴展ContentResult
的結果。你可以參考它
這是一個演示:Controller:
public ActionResult DownloadFile()
{
//return Content("alert('No data was found to create a CSV file!');", "application/javascript");
return new JavaScriptResult("alert('No data was found to create a CSV file!');");
}
public ActionResult DownloadFile1() {
return View();
}
public class JavaScriptResult : ContentResult
{
public JavaScriptResult(string script)
{
this.Content = script;
this.ContentType = "application/javascript";
}
}
下載文件1:
@{
ViewData["Title"] = "DownLoadFile1";
}
<h1>DownLoadFile1</h1>
<div>
<partial name="DownLoadFile" />
</div>
@section scripts{
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
$(function () {
$.getScript("/Test/DownloadFile");
});
</script>
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.