I am trying to create an application in which a user can upload .CSV files into an SQL database that I have created. I have become a little confused when it comes to actually getting the file path from the view and writing it into the database.
First off, here is the model that I'm working off:
public class OutstandingCreditCsv
{
[CsvColumn(FieldIndex = 1, CanBeNull = false)]
public string PoNumber { get; set; }
[CsvColumn(FieldIndex = 2, OutputFormat = "dd MMM HH:mm:ss")]
public DateTime CreditInvoiceDate { get; set; }
[CsvColumn(FieldIndex = 3)]
public string CreditInvoiceNumber { get; set; }
[CsvColumn(FieldIndex = 4, CanBeNull = false, OutputFormat = "C")]
public decimal CreditInvoiceAmount { get; set; }
}
And here is the controller code so far:
public ActionResult Index()
{
CsvFileDescription inputFileDescription = new CsvFileDescription
{
SeparatorChar = ',',
FirstLineHasColumnNames = true
};
var context = new CsvContext();
IEnumerable<OutstandingCreditCsv> csvList =
context.Read<OutstandingCreditCsv>("C:/Users/BlahBlah/Desktop/CsvUploadTestFile.csv", inputFileDescription);
foreach (OutstandingCreditCsv line in csvList)
{
}
return View();
}
There are two areas where I need a little guidance. I'm not sure how to pass the file from the view to the controller, lets say my view is something simple like this:
<form action="" method="POST" enctype="multipart/form-data">
<table style="margin-top: 150px;">
<tr>
<td>
<label for="file">Filename:</label>
</td>
<td>
<input type="file" name="file" id="file"/>
</td>
<td><input type="submit" value="Upload"/></td>
</tr>
</table>
</form>
I'm also unsure how I would actually loop the csv data into my database. You can see the foreach loop in my controller is empty. Any help would be appreciated. Thanks!
foreach (var item in model) { item.PoNumber item.CreditInvoiceDate item.CreditInvoiceNumber item.CreditInvoiceAmount }Usually I would docc.PoNumber = item.PoNumber, but that can't be done here