In this article I will explain with an example, how to upload, read and display CSV file (Text File) data in ASP.Net MVC Razor.
CSV file is a Text file which contains Comma Separated (Comma Delimited) values. The data from a CSV file will be read and then after separating the values, the data will be populated in HTML Table (Grid) format.
Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.
 
 
Namespaces
You will need to import the following namespace.
using System.IO;
 
 

Model
Following is a Model class named CustomerModel with three properties i.e. CustomerId, Name and Country.
public class CustomerModel
{
    ///<summary>
    /// Gets or sets CustomerId.
    ///</summary>
    public int CustomerId { get; set; }
 
    ///<summary>
    /// Gets or sets Name.
    ///</summary>
    public string Name { get; set; }
 
    ///<summary>
    /// Gets or sets Country.
    ///</summary>
    public string Country { get; set; }
}
 
 
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, an empty Generic List collections of the CustomerModel class object is returned.
 
Action method for handling POST operation for uploading and reading CSV file
This Action method gets called when the CSV File is selected and the Import Button is clicked, and it gets the uploaded file in the HttpPostedFileBase parameter.
Note: In case the HttpPostedFileBase parameter is appearing NULL, then please refer the article, ASP.Net MVC: HttpPostedFileBase always returns NULL.
 
The uploaded CSV file is saved to a folder named Uploads.
The CSV file data is read into a String variable using the File class ReadAllText method.
The CSV file data is split using New Line (\n) and Comma (,) characters and using a loop the data is copied into the Generic List collection of CustomerModel class objects which is then sent to the View.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View(new List<CustomerModel>());
    }
 
    [HttpPost]
    public ActionResult Index(HttpPostedFileBase postedFile)
    {
        List<CustomerModel> customers = new List<CustomerModel>();
        string filePath = string.Empty;
        if (postedFile != null)
        {
            string path = Server.MapPath("~/Uploads/");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
 
            filePath = path + Path.GetFileName(postedFile.FileName);
            string extension = Path.GetExtension(postedFile.FileName);
            postedFile.SaveAs(filePath);
 
            //Read the contents of CSV file.
            string csvData = System.IO.File.ReadAllText(filePath);
 
            //Execute a loop over the rows.
            foreach (string row in csvData.Split('\n'))
            {
                if (!string.IsNullOrEmpty(row))
                {
                    customers.Add(new CustomerModel
                    {
                        CustomerId = Convert.ToInt32(row.Split(',')[0]),
                        Name = row.Split(',')[1],
                        Country = row.Split(',')[2]
                    });
                }
            }
        }
 
        return View(customers);
    }
}
 
 
View
Inside the View, the CustomerModel class is declared as IEnumerable which specifies that it will be available as a Collection.
The View consists of an HTML FileUpload element and a Submit Button enclosed in a Form element.
The HTML Form has been created using the Html.BeginForm method which accepts the following parameters.
ActionNameName of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
HtmlAttributes – This array allows to specify the additional Form Attributes. Here we need to specify enctype = “multipart/form-data” which is necessary for uploading Files.
For displaying the records, an HTML Table is used. A loop will be executed over the Model which will generate the HTML Table rows with the CSV file data.
@using Read_CSV_MVC.Models
@model IEnumerable<CustomerModel>
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <input type="file" name="postedFile"/>
        <input type="submit" value="Import"/>
    }
    @if (Model.Count() > 0)
    {
        <hr/>
        <table cellpadding="0" cellspacing="0">
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Country</th>
            </tr>
            @foreach (CustomerModel customer in Model)
            {
                <tr>
                    <td>@customer.CustomerId</td>
                    <td>@customer.Name</td>
                    <td>@customer.Country</td>
                </tr>
            }
        </table>
    }
</body>
</html>
 
 
Screenshots
The CSV File
Upload, Read and Display CSV file (Text File) data in ASP.Net MVC
 
HTML Grid displaying CSV data
Upload, Read and Display CSV file (Text File) data in ASP.Net MVC
 
 
Downloads