I'm developing an ASP.NET MVC3 application. I have a controller for file download:
public ActionResult PDF(string id)
{
try
{
// here I unzip a file, DownName comes from here
Response.Clear();
Response.AddHeader("Content-Disposition",
"attachment; filename=" + id + ".pdf");
Response.ContentType = "application/pdf";
Response.WriteFile(DownName);
Response.Flush();
Response.Close();
System.IO.File.Delete(DownName);
return View();
}
catch (Exception)
{
message = "File not found.";
}
return Json(new { message = message }, JsonRequestBehavior.AllowGet);
}
At client side, I need to get this PDF file. However, if the file couldn't be found, I will alert a text like "File not found.". I tried many ways and came into this finally:
$(function(){
$(".pdf").click(function(e) {
e.preventDefault();
$.post("@Url.Action("PDF","Helper")",{id : $(this).data("id")},function(data){
if(data.message == "File not found.") {
alert(data.message);
} else {
alert(data);
}
});
});
});
If file couldn't be found, I can successfully alert error message. How can I open a save dialog box for the data here? Any other way I can work for the controller is appreciated, too.
EDIT: I can download the file easily if I call the controller like this:
<a href="../../Helper/PDF/@Model.ID">Download PDF</a>
However, if the result of this isn't the file and JSON, page is redirected to a blank page displaying the JSON object. I want it to be alert to screen as I said before. I appreciate workarounds with this method, too.