如何使用ContentResult从控制器actionresult返回javascript?

时间:2020-06-08 18:16:57

标签: javascript c# asp.net-mvc asp.net-core

我想知道当文件夹中未创建通常生成的文件时如何返回JavaScript警报。运行else语句时,它将在浏览器选项卡顶部返回文字文本,而不是我要查找的警报。看起来像这样:

Browser text

代码:

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>");

    }
}

1 个答案:

答案 0 :(得分:0)

首先,您可以使用方法public virtual ContentResult Content(string content, string contentType);而不是public virtual ContentResult Content(string content);

控制器:

public ActionResult DownloadFile()
        {
            return Content("alert('No data was found to create a CSV file!');", "application/javascript");
        }

此外,您还可以编写一个包含参数构造函数并扩展ContentResult的结果。您可以参考it

这是一个演示作品: 控制器:

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";
        }
    }

DownloadFile1:

@{
    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>
}

结果: enter image description here