CSVHelper与ASP.NET MVC 3

CSVHelper与ASP.NET MVC 3

问题描述:

我想上传一个CSV文件,并使用MVC3实现CSVHelper主管。

I am trying to upload a csv file and implement the CSVHelper competent using MVC3.

https://github.com/JoshClose/CsvHelper

我还没有发现使用这种带有一个文件上传的一个例子。基本上,我需要采取的CSV文件并映射到实体对象并保存到数据库。这里是我的实体:

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; }

    }

上传处理程序:

 [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);
        }

我不知道如何通过CSV文件循环,并保存到数据库。没有任何人有一个例子吗?

I'm not sure how to loop through the CSV file and save to the DB. Does anybody have an example?

我会建议你使用自定义模型粘合剂用于此目的,以避免与CSV解析code塞满您的控制器逻辑:

I would recommend you using a custom model binder for this purpose to avoid cluttering your controller logic with CSV parsing code:

public class SurveyEmailListModelsModelBinder: DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var csv = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        var file = ((csv.RawValue as HttpPostedFileBase[]) ?? Enumerable.Empty<HttpPostedFileBase>()).FirstOrDefault();

        if (file == null || file.ContentLength < 1)
        {
            bindingContext.ModelState.AddModelError(
                "", 
                "Please select a valid CSV file"
            );
            return null;
        }

        using (var reader = new StreamReader(file.InputStream))
        using (var csvReader = new CsvReader(reader))
        {
            return csvReader.GetRecords<SurveyEmailListModels>().ToArray();
        }
    }
}

将在的Application_Start 注册:

ModelBinders.Binders.Add(
    typeof(SurveyEmailListModels[]), 
    new SurveyEmailListModelsModelBinder()
);

现在,我们可以有一个控制器:

And now we could have a controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(SurveyEmailListModels[] model)
    {
        if (!ModelState.IsValid)
        {
            return View();
        }

        ... store the model into the database 

        return Content("Thanks for uploading");
    }
}

和一个视图:

@Html.ValidationSummary()
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="model" />
    <button type="submit">OK</button>
}