ASP.NET MVCでCSVダウンロード
test.cshtml
<button class="btnCsvDownloadList" type="button">CSVダウンロード</button>
<script src="~/Scripts/pages/test.js"></script>
test.js
$('.btnCsvDownloadList').click(function () {
var documentUrl = document.URL;
var baseUrl = documentUrl.substring(0, documentUrl.indexOf('currentPageName'));
var mySiteUrl = 'http://mysite.com'
location.href = mySiteUrl + '/CsvDownloadList';
});
TestController.cs
[Route("CsvDownloadList")]
public ActionResult CsvDownloadList(string areaType, string partner)
{
var fileName = string.Format("{0:yyyyMMdd}.csv", DateTime.Now);
return File(logic.GetCsvData(), "text/csv", fileName);
}
TestLogic.cs
public byte[] GetCsvData()
{
var stream = new MemoryStream();
var csvWriter = new StreamWriter(stream, Encoding.GetEncoding("shift-jis"));
csvWriter.WriteLine(String.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8}",
"1",
"名前",
"名前カナ",
"012-3456-7890",
"住所",
"0",
"何かの内容",
"何かの内容2",
"何かの内容3"));
csvWriter.Flush();
return stream.ToArray();
}