Reputation: 8416
Usually, in ASP.NET, MVC or otherwise, we make the client download a file by having the user click a link/button; I assume this link/button action goes to the correct controller then redirects back to the main page. However, how can I cause the download from some intermediate controller, during a series of redirects?
Basically, when the user clicks a button to create a PDF, the action goes to PdfController to create the PDF, then, since I'm assuming he/she wants to download the PDF anyway (if he/she doesn't, he/she can always click "No"), I want to have the browser download the PDF before the page gets rendered again. If I haven't lost you yet, how do I accomplish this?
Here's a sample of what I have so far. Button that starts the action:
<a class="btn btn-primary col-md-2 col-md-offset-1" href="@Url.Action("MakePdf", "Pdf")">Create PDF</a>
PdfController's MakePdf() method:
public ActionResult MakePdf()
{
string PdfUrl = Environment.GetEnvironmentVariable("HOMEDRIVE") + Environment.GetEnvironmentVariable("HOMEPATH") + "/Sites/Bems/PDF/UserPdfs/report" + Id + ".pdf";
// create the PDF at this PdfUrl
return RedirectToAction("ShowPdf", "Pdf", new { PdfUrl = PdfUrl });
}
PdfController's ShowPdf() method, redirected from the previous MakePdf() method:
public ActionResult ShowPdf(string PdfUrl)
{
if (System.IO.File.Exists(PdfUrl))
{
return File(PdfUrl, "application/pdf"); // Here is where I want to cause the download, but this isn't working
}
else
{
using (StreamWriter sw = System.IO.File.CreateText(PdfUrl))
{
sw.WriteLine("A PDF file should be here, but we could not find it.");
}
}
return RedirectToAction("Edit", "Editor"); // Goes back to the editing page
}
I'm trying to cause the download at the place in the code I specified, but I'm not sure how to cause it. Usually you return it somehow to the view, whereas here I'm calling an object, I think, but I'm really fuzzy on how that all works. Regardless, something I'm doing isn't working. Any ideas on what that is?
Upvotes: 0
Views: 804
Reputation: 1189
You can't return the ViewResult RedirectToAction("Edit", "Editor")
and in the same response a FileResult File(PdfUrl, "application/pdf")
To accomplish your task you could follow this scenario:
RedirectToAction("Edit", "Editor");
Upvotes: 1