Suppose you have a list of objects and wanted to generate CSV and download whenever the user clicks on the export button.



Create a button on with HTML .net helper method.

UI Part

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

The first argument is a text you want to show that to the user, the second one is the controller action name you will going to call that will generate and download the report of the list of objects of your choice.

Controller Action

Controller action would be something like this below:

        public FileResult DownloadReport()
            var lstData = new DataDbHandler().GetDetails();
            var sb = new StringBuilder();
            foreach (var data in lstData)
            return File(new UTF8Encoding().GetBytes(sb.ToString()), "text/csv", "export.csv");

First, Get the required list.
Second, Create a string builder object.
And go through from each of the items from the list, and append each data in a separate line with comma-separated.
And return file object, the First argument is content, the second is the type of content and the third one is the name of the file you will see after download.

Ding Dong, Your download will be ready 😉

As simple is that, this action will create a CSV(Comma Separated Values) and start downloading with ease.

This is the easiest and simplest solution you will implement.

-3 Points