【问题标题】:How can I return javascript from a controller actionresult using ContentResult?如何使用 ContentResult 从控制器 actionresult 返回 javascript?
【发布时间】:2020-09-27 19:24:05
【问题描述】:

我想知道当通常生成的文件未在文件夹中创建时如何返回 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>");

    }
}

【问题讨论】:

  • 我不确定你应该这样做
  • Content() 将 http 内容类型标头设置为“text/plain”。这就是为什么不呈现 html 的原因。请参阅docs.microsoft.com/en-us/dotnet/api/… 以返回具有正确状态代码的 html
  • @ChristophLütjen 我添加了一个带有“text/javascript”的 contentType 参数,这似乎并没有改变输出。
  • 以您的示例为例,您返回的是 html (text/html) 而不是 javascript。

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


【解决方案1】:

首先你可以使用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";
        }
    }

下载文件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>
}

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    • 2020-06-07
    • 1970-01-01
    • 2010-09-13
    相关资源
    最近更新 更多