Monthly Archives: August 2016

Downloading a file from MVC controller to .ascx using javascript ajax

Here is a simple way to download a file to a .net user control from a newer MVC controller.

The Controller code:

public FileResult DownloadSweetFile()
{
var downloadDirectory = _appSettings.PathToFile;
var filePathAndName = Path.Combine(downloadDirectory, "MySweetFile.pdf");

var cd = new System.Net.Mime.ContentDisposition
{
FileName = "MySweetFile.pdf",
Inline = false, //NOTE: This forces always prompting the user to download, not open file in the browser
};
Response.AppendHeader("Content-Disposition", cd.ToString());

return File(filePathAndName, "application/pdf");
}

I used a button on the page to fire the javascript

button type="button" id="btnSweetDownload" onclick="downloadSweetFile();" Click here to download a Sweet File!
(I removed the button tag so this will show correctly)

And here is the javascript to use in the .ascx file:

function downloadSweetFile() {
var url = '/MyControllerName/DownloadSweetFile';
window.location = url;
};