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