簡體   English   中英

如何使用 ContentResult 從 controller actionresult 返回 javascript?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM