Gerard Gerard - 3 months ago 22
jQuery Question

Export to CSV using MVC, C# and jQuery

I am trying to export a list to a CSV file.
I got it all working up to the point I want to write to file to the response stream. This doesn't do anything.

Here is my code:

Call the the method from the page.

$('#btn_export').click(function () {

The code in the controller is as follows:

public void Export()
var filter = Session[FilterSessionKey] != null ? Session[FilterSessionKey] as SubscriberFilter : new SubscriberFilter();

var predicate = _subscriberService.BuildPredicate(filter);
var compiledPredicate = predicate.Compile();
var filterRecords = _subscriberService.GetSubscribersInGroup().Where(x => !x.IsDeleted).AsEnumerable().Where(compiledPredicate).GroupBy(s => s.Subscriber.EmailAddress).OrderBy(x => x.Key);

catch (Exception exception)
Logger.WriteLog(LogLevel.Error, exception);

private void ExportAsCSV(IEnumerable<IGrouping<String, SubscriberInGroup>> filterRecords)
var sw = new StringWriter();
//write the header
sw.WriteLine(String.Format("{0},{1},{2},{3}", CMSMessages.EmailAddress, CMSMessages.Gender, CMSMessages.FirstName, CMSMessages.LastName));

//write every subscriber to the file
var resourceManager = new ResourceManager(typeof(CMSMessages));
foreach (var record in filterRecords.Select(x => x.First().Subscriber))
sw.WriteLine(String.Format("{0},{1},{2},{3}", record.EmailAddress, record.Gender.HasValue ? resourceManager.GetString(record.Gender.ToString()) : "", record.FirstName, record.LastName));

Response.AddHeader("Content-Disposition", "attachment; filename=adressenbestand.csv");
Response.ContentType = "text/csv";

But after
nothing is happening. Is it even possible to save a file this way?



The response headers I see when I click the button are:

HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/csv; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 2.0
Content-Disposition: attachment; filename=adressenbestand.csv
X-Powered-By: ASP.NET
Date: Wed, 12 Jan 2011 13:05:42 GMT
Content-Length: 113

Which seem OK to me..


I got rid of the jQuery part en replaced it by an hyperlink and this is working fine for me now:

<a class="export" href="NewsLetter/Export">exporteren</a>


yan.kun was on the right track but this is much much easier.

    public FileContentResult DownloadCSV()
        string csv = "Charlie, Chaplin, Chuckles";
        return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "Report123.csv");