In this article I will explain with an example, how to download
CSV file from Database in ASP.Net MVC.
Database
I have made use of the following table tblFiles with the schema as follow.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Model
The Model class consists of the following properties.
public class FileModel
{
public int Id { get; set; }
public string Name { get; set; }
public string ContentType { get; set; }
public byte[] Data { get; set; }
}
Namespaces
You will need to import the following namespaces.
using System.Data.SqlClient;
using System.Configuration;
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, the GetFiles method is called.
Inside the
GetFiles method, the records from the
tblFiles table are fetched using
DataReader and Generic List of
FileModel class objects is populated.
Finally, the Generic List of FileModel class objects is returned to the View.
Action method for handling POST operation for downloading Files
When the
Download link inside the
HTML Table (Grid) is clicked, the Id of the particular file is sent to this Action method and using the File Id, the File’s binary data is fetched from the database using
ADO.Net.
Note: The following Action method performs File Download and hence the return type is set to FileResult.
Finally, the File is downloaded using the File function.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View(GetFiles());
}
[HttpPost]
public FileResult DownloadFile(int? fileId)
{
byte[] bytes;
string fileName, contentType;
string sql = "SELECT Name, Data, ContentType FROM tblFiles WHERE Id=@Id";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("@Id", fileId);
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["Data"];
contentType = sdr["ContentType"].ToString();
fileName = sdr["Name"].ToString();
}
con.Close();
}
}
return File(bytes, contentType, fileName);
}
private static List<FileModel>GetFiles()
{
List<FileModel> files = new List<FileModel>();
string sql = "SELECT Id, Name FROM tblFiles";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
files.Add(new FileModel
{
Id = Convert.ToInt32(sdr["Id"]),
Name = sdr["Name"].ToString()
});
}
}
con.Close();
}
}
return files;
}
}
View
HTML Markup
Inside the View, in the very first line the FileModel class is declared as IEnumerable which specifies that it will be available as a Collection.
The View consists of a Form.
Displaying the Files
For displaying the records, an
HTML Table is used. A FOR EACH loop will be executed over the Model which will generate the
HTML Table rows with the
tblFiles records.
Form for Downloading the File
The Form consists of an
HTML HiddenField and a Hidden Submit Button.
When any
Download Link inside the
HTML Table (Grid) is clicked, then the
DownloadFile JavaScript function is called, which sets the
FileId into the HiddenField and calls the click event of the
Submit button which submits the Form.
When the Form is submitted, the DownloadFile Action method is called, which performs the File download operation.
@model IEnumerable<Download_CSV_Database_MVC.Models.FileModel>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("DownloadFile", "Home", FormMethod.Post))
{
<input type="hidden" id="hfFileId" name="FileId" />
<input type="submit" id="btnDownload" value="Download" style="display:none" />
}
<hr />
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<th style="width:120px">File Name</th>
<th style="width:80px"></th>
</tr>
@foreach (var file in Model)
{
<tr>
<td>@file.Name</td>
<td><a href="javascript:;" onclick="DownloadFile(@file.Id)">Download</a></td>
</tr>
}
</table>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
function DownloadFile(fileId) {
$("#hfFileId").val(fileId);
$("#btnDownload")[0].click();
};
</script>
</body>
</html>
Screenshot
Downloads