Comma Separated Value (CSV) in MVC Using Ajax

Introduction

Comma Separated Value (CSV) is a format for storing data with the values separated by commas. Usually in applications, there is a requirement to upload CSV files only using the HTML uploader and retrieve the values and save to the database. Let's explore how and understand each step. The following image shows what a CSV file looks like:



The first row in the document image depicts the column headers. The following rows are the values for the headers that we will be retrieving and saving into the database. Remember, we will also need to delete the first and the last rows since they would not be saved into the database and in fact they cannot be.

Get started

To start with this we need to have a sample CSV file to test. I will be using the sample as specified in the image. First of all we need to create a view model for holding the values while looping through the file data. Let's have a look at how our viewmodel would look like:
  1. public class CsvRecordsViewModel  
  2. {  
  3.     public string Name{get;set;}  
  4.     public string School{get;set;}  
  5.     public int Age{get;set;}  
  6.     public string DOB{get;set;}  
  7.     public string ParentName{get;set;}  

This is the view model that will hold the values for each row in the CSV file that we will be retrieving by running through a loop. But before that we need to fetch the file and then send it to the server for processing. We will be doing this using Ajax:
  1. $("#submitBox").click(function () {  
  2.     var fileUpload = document.getElementById("IDofTheUploader");  
  3.     if (fileUpload .value != null) {  
  4.         var uploadFile = new FormData();  
  5.         var files = $("#IDofTheUploader").get(0).files;  
  6.         // Add the uploaded file content to the form data collection  
  7.         if (files.length > 0) {  
  8.             uploadFile.append("CsvDoc", files[0]);  
  9.             $.ajax({  
  10.                 url: "/Controller/Action",  
  11.                 contentType: false,  
  12.                 processData: false,  
  13.                 data: uploadFile,  
  14.                 type: 'POST',  
  15.                 success: function () {  
  16.                    alert("Successfully Added & processed");  
  17.                 }  
  18.             });  
  19.         }  
  20.     }  
  21. }); 
Let's understand what happens inside the snippet mentioned above. When the user selects a file from the browse window, he needs to select a CSV file, nothing other than that. For that we need to give a check both at the client level and the server level. The following snippet shows how to restrict the user from uploading some other extension file:
  1. $("#IDofTheUploader").change(function () {  
  2.        var selectedText = $("#IDofTheUploader").val();  
  3.        var extension = selectedText.split('.');  
  4.        if (extension[1] != "csv") {  
  5.            $("#IdofTheTextBoxUpload").focus();  
  6.            alert("Please choose a .csv file");  
  7.            return;  
  8.        }  
  9.        $("#IdofTheTextBoxUpload").val(selectedText);  
  10.   
  11.    }); 
Thus, if a user tries to upload some other extension file, he gets an alert saying Please choose a CSV file. As you can see we have checked based on the upload Id input change function and the last line, if the file extension is .csv then add the file path text into the text box. Then after that when the user hits/clicks Submit, then the ".click" function executes. At first we get the fileUploadId, then we check if the fileUpload value is not null. It automatically treats it as a file since it includes already the input HTML element of type File. Then we declare a variable of type FormData that will contain the entire file and the details. Then we get the files using the fileUploadId. If the files exist that we check from the length, then the file is appended into the FormData type variable declared earlier, then we make the ajax call to the server. Just keep in mind to add the ProcessData and the contentType to be ed in the ajax call. We send the data with the same name as uploadFile (of type FormData()). Then this the file is sent to the server where we read though the file using the InputStream. Let's first have a look at the snippet:
  1.       /// <summary>  
  2.      ///  Controller method to validate the csv document before upload  
  3.      /// </summary>  
  4.      /// <returns></returns>  
  5.      public ActionResult UploadCsvFile()  
  6.      {  
  7.          var attachedFile = System.Web.HttpContext.Current.Request.Files["CsvDoc"];  
  8.          if (attachedFile == null || attachedFile.ContentLength <= 0) return Json(null);  
  9.          var csvReader = new StreamReader(attachedFile.InputStream);  
  10.          var uploadModelList = new List<CsvRecordsViewModel>();  
  11.          string inputDataRead;  
  12.          var values = new List<string>();  
  13.          while ((inputDataRead = csvReader.ReadLine()) != null)  
  14.          {  
  15.                  values.Add(inputDataRead.Trim().Replace(" """).Replace(","" "));  
  16.              
  17.          }  
  18.          values.Remove(values[0]);  
  19.          values.Remove(values[values.Count - 1]);  
  20.   using(var context = new Entities()){  
  21.          foreach (var value in values)  
  22.          {  
  23.              var uploadModelRecord = new CsvRecordsViewModel();  
  24.              var eachValue = value.Split(' ');  
  25.              uploadModelRecord.Name = eachValue[0]!=""?eachValue[0]:string.Empty;  
  26.              uploadModelRecord.School = eachValue[1] != "" ? eachValue[1] : string.Empty;  
  27.              uploadModelRecord.Age = eachValue[2] != "" ? eachValue[2] : string.Empty;  
  28.              uploadModelRecord.DOB = eachValue[3] != "" ? eachValue[3] : string.Empty;  
  29.              uploadModelRecord.ParentName = eachValue[4] != "" ? eachValue[4]:string.Empty;  
  30.              uploadModelList.Add(newModel);// newModel needs to be an object of type ContextTables.  
  31.     context.TableContext.Add(uploadModelRecord);  
  32.     }  
  33. context.SaveChanges();  
  34. }  
  35.          return Json(null);  
  36.      } 
The preceding is the action method where the server-side operation runs. Pardon me for using a context object inside the controller, this is just for the demo, please "Do Not Add context to the controller". Now look at the preceding snippet for the attachedFile, this now contains the file that we had sent as data from the ajax call and accessed using the current request in the context using the same name as the FormData() variable append Name. Then we create a new object for the Csv Reader that is of type StreamReader() that takes the attachedFile's InputStream as parameter. Then we declare a string variable that will have each row or line read from the CSV file using the csvReader object ReadLine() property. If that is not null then we manipulate the string row and then add each row now to a list of string type objects. We replace the spaces with empty and the comma with spaces so that it will be easy to split and start extracting the values. Then the most important task is to remove the first and last row in the CSV file that have been retrieved and saved into the vaues object. Thus we remove the 0th element and the Count - 1 value (row) and then we work on our creation of the viewModel and then save that into the database table.

Conclusion

This is a very simple and handy code snippet article that might be useful at any moment of the application. There are many records that can be retrieved and manipulated using this snippet and either mail or create a viewmodel and save as we did above. Thus when we hear it may seem hard and complex but it is that simple, since without saving/uploading the file into the File System we are directly readig the file at runtime. I hope this becomes handy for all. I am not an expert, so suggestions and corrections are humbly welcome. Thanks for your patience.

Up Next
    Ebook Download
    View all
    Learn
    View all