MVC 4: How do I download a list as a CSV?

I added a simple link in my view

@Html.ActionLink("Export Data", "ExportData")

and a simple method in my controller to take care of the download

public ActionResult ExportData()
{
return DownloadCSV();
}

public FileContentResult DownloadCSV()
{
string csv = string.Concat(from x in db.MyData
  select x.ID + ","
  + x.Name + "\n");

return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv",  string.Format("Export.{0}.csv", DateTime.Now.ToString("yyyy-MM-dd_HHmmss")));
}

Comments

Popular posts from this blog

SharePoint 2013: Error updating managed account credentials

How can I call a JIRA api through Powershell?