sjohn285
sjohn285

Reputation: 405

How can I return javascript from a controller actionresult using ContentResult?

I'm wondering how I can return a javascript alert when the file that usually gets generated is not created in the folder. When the else statement is ran, it returns the literal text at the top of the browser tab instead of the alert that I am looking for. It looks like this:

Browser text

Code:

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

    }
}

Upvotes: 3

Views: 2117

Answers (1)

Yiyi You
Yiyi You

Reputation: 18199

Firstly you can use the method public virtual ContentResult Content(string content, string contentType); rather than public virtual ContentResult Content(string content);

Controller:

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

In addition,you can also write a result which has a Parametrical constructor and extends ContentResult.You can refer to it

Here is a demo worked: 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";
        }
    }

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

Result: enter image description here

Upvotes: 2

Related Questions