简体   繁体   中英

How to call a custom action result from Javascript

I have a custom ActionResult that I pass in a url string to and it will stream a file back to me. How would I call this from Javascript file? Since I have to pass a string I don't think I can use jQuery's $.post() or .ajax() methods but I could be wrong. I also can not use Razor's @Html.ActionLink method for reasons involving the ? Here is my code.

public class ReportResult : ActionResult
{
    private readonly string _fileName;
    public ReportResult(string fileName)
    {
        _fileName = fileName;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        var cd = new ContentDisposition
        {
            FileName = _fileName,
            Inline = false
        };
        var response = context.HttpContext.Response;
        response.ContentType = "application/pdf";
        response.Headers["Content-Disposition"] = cd.ToString();

        using (var client = new WebClient())
        using (var stream = client.OpenRead(_fileName))
        {
            stream.CopyTo(response.OutputStream);
        }            
    }
}

The Controller Method that references it.

public ActionResult DownloadPdf(string filePath)
{
    return new ReportResult(filePath);
}

So the reason why I was having issues with the file opening up in a window rather than downloading was due to the Controller and Action method part of the url string getting cut off before it was getting passed to location.href in the Javascript. Below is the new Javascript that will open the url and immediately download the PDF file.

location.href = "/Controller/DownloadPdf?filePath=" + pdfUrl;

Thanks to @SLacks in the comments for some guidance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM