How to create and download file with Ajax in ASP.NET MVC

Introduction

When you use the Ajax call in ASP.NET MVC, you just can return a JSON object but not a file, if you want to do that, you need to create and save the file in server and return it’s path to Ajax, after that, you can call a redirect link for download the file, because this is a temp file, so you should need to delete it after download.

[HttpGet]
[DeleteFileAttribute] //Action Filter, it will auto delete the file after download, I will explain it later
public ActionResult Download(string file)
{
//get the temp folder and file path in server
string fullPath = Path.Combine(Server.MapPath("~/temp"), file);
//return the file for download, this is an Excel so I set the file content type to "application/vnd.ms-excel"
return File(fullPath, "application/vnd.ms-excel", file);
}

3. We need to auto delete the file after download, so need to create an Action Filter