In this article I will explain with an example, how to export
WebGrid to
CSV (Text) file in ASP.Net Core MVC.
The
WebGrid will be populated from database using
Entity Framework and then the records from the database will be exported and downloaded as Microsoft
CSV (Text) file in ASP.Net Core MVC.
MVC6 Grid for ASP.Net Core
This article makes use of
MVC6 Grid library for implementing
WebGrid, as it is not available by default in .Net Core.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Model
The Model class consists of the following properties.
public class Customer
{
public string CustomerID { get; set; }
public string ContactName { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
Database Context
Once the
Entity Framework is configured and connected to the database table, the Database Context will look as shown below.
using Microsoft.EntityFrameworkCore;
namespace Export_WebGrid_CSV_MVC_Core
{
public class DBCtx : DbContext
{
public DBCtx(DbContextOptions<DBCtx> options) : base(options)
{
}
public DbSet<Customer> Customers { get; set; }
}
}
Namespaces
You need to import the following namespace.
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, the Top 10 records are fetched from the
Customers table using
Entity Framework and returned to the View.
Action method for handling the CSV (Text) files Export and Download operation
This Action method is executed when the Export Button is clicked.
Note: The following Action method performs File Download operation. Hence the return type is set to FileResult.
Inside this Action method, the Top 10 records are fetched from the
Customers table using
Entity Framework.
Then, a FOREACH loop is executed over the records fetched using
Entity Framework and a comma separated (delimited) string is generated which is ultimately converted to a BYTE Array using the
GetBytes method of
Encoding class.
Finally, the BYTE Array is exported and downloaded as
CSV (Text) file using the
File method which accepts type and name of the
CSV (Text) file to be downloaded.
public class HomeController : Controller
{
private DBCtx Context { get; }
public HomeController(DBCtx _context)
{
this.Context = _context;
}
public IActionResult Index()
{
return View(this.Context.Customers.Take(10).ToList());
}
[HttpPost]
public FileResult Export()
{
string[] columnNames = new string[] { "CustomerId", "ContactName", "City", "Country" };
var customers = this.Context.Customers.Take(10).ToList();
//Build the CSV file data as a Comma separated string.
string csv = string.Empty;
foreach (string columnName in columnNames)
{
//Add the Header row for CSV file.
csv += columnName + ',';
}
//Add new line.
csv += "\r\n";
foreach (var customer in customers)
{
//Add the Data rows.
csv += customer.CustomerID.Replace(",", ";") + ',';
csv += customer.ContactName.Replace(",", ";") + ',';
csv += customer.City.Replace(",", ";") + ',';
csv += customer.Country.Replace(",", ";") + ',';
//Add new line.
csv += "\r\n";
}
//Download the CSV file.
byte[] bytes = Encoding.ASCII.GetBytes(csv);
return File(bytes, "text/csv", "Grid.csv");
}
}
View
Inside the View, in the very first line the Customer Model is declared as IEnumerable which specifies that it will be available as a collection.
The ASP.Net TagHelpers, NonFactors.Mvc.Grid namespaces are inherited.
Then, the following CSS file is inherited.
1. mvc-grid.css
Displaying the records
For displaying the records, MVC6 Grid is used.
The IEnumerable collection of Customer Model class object is passed to the Grid function of the MVC6 Grid HTML Helper class.
Exporting MVC6 Grid to CSV (Text) file
Below the MVC6 Grid, there is an HTML Form created with following ASP.Net Tag Helpers attributes.
asp-action – Name of the Action. In this case the name is Export.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Form consists of a Submit Button.
When the
Export Button is clicked, the
MVC6 Griddata will be exported and downloaded as
CSV (Text) file.
@model IEnumerable<Export_WebGrid_CSV_MVC_Core.Models.Customer>
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@using NonFactors.Mvc.Grid;
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="~/css/mvc-grid/mvc-grid.css" rel="stylesheet" />
</head>
<body>
<h4>Customers</h4>
<hr />
@(Html.Grid(Model).Build(columns =>
{
columns.Add(model => model.CustomerID).Titled("CustomerID");
columns.Add(model => model.ContactName).Titled("ContactName");
columns.Add(model => model.City).Titled("City");
columns.Add(model => model.Country).Titled("Country");
})
)
<br /><br />
<form method="post" asp-action="Export" asp-controller="Home">
<input type="submit" id="btnSubmit" value="Export" />
</form>
</body>
</html>
Screenshots
WebGrid
Exported CSV (Text) file
Downloads