I am trying to upload a csv file and implement the CSVHelper competent using MVC3.
https://github.com/JoshClose/CsvHelper
I haven't found an example of using this with a file upload. Basically, I need to take the the CSV file and map to entity objects and save to the DB. Here are my entities:
public class SurveyEmailListModels
{
[Key]
public int SurveyEmailListId { get; set; }
[CsvField(Index = 0)]
public int ProgramId { get; set; }
[CsvField(Index = 1)]
public virtual SurveyProgramModels SurveyProgramModels { get; set; }
[CsvField(Index = 2)]
public string SurveyEmailAddress { get; set; }
[CsvField(Index = 3)]
public bool SurveyResponded { get; set; }
}
Upload Handler:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file, SurveyEmailListModels surveyemaillistmodels, int id)
{
if (file != null && file.ContentLength > 0)
{
// Collect file and place into directory for source file download
var appData = Server.MapPath("~/csv/");
var filename = Path.Combine(appData, Path.GetFileName(file.FileName));
file.SaveAs(filename);
// surveyemaillistmodels.SurveyEmailAddress = "test@test.com";
// surveyemaillistmodels.SurveyResponded = true;
// surveyemaillistmodels.ProgramId = id;
db.SurveyEmailListModels.Add(surveyemaillistmodels);
db.SaveChanges();
return Content(filename);
}
return Json(true);
}
I'm not sure how to loop through the CSV file and save to the DB. Does anybody have an example?