繁体   English   中英

如何从Javascript调用自定义操作结果

[英]How to call a custom action result from Javascript

我有一个自定义ActionResult,我将其传递给url字符串,它将把文件流回给我。 我如何从Javascript文件中调用它? 因为我必须传递一个字符串,所以我认为我不能使用jQuery的$.post().ajax()方法,但是我可能是错的。 由于涉及?的原因,我也无法使用Razor的@Html.ActionLink方法。 这是我的代码。

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

引用它的Controller方法。

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

因此,我在窗口中打开文件而不是下载时遇到问题的原因是由于url字符串的Controller和Action方法部分在传递给Javascript中的location.href之前已被切断。 下面是新的Javascript,它将打开url并立即下载PDF文件。

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

感谢@SLacks在评论中的一些指导。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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