4

csv ファイルをアップロードし、MVC3 を使用して有能な CSVHelper を実装しようとしています。

https://github.com/JoshClose/CsvHelper

ファイルのアップロードでこれを使用する例は見つかりませんでした。基本的に、CSV ファイルを取得してエンティティ オブジェクトにマップし、DB に保存する必要があります。ここに私のエンティティがあります:

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 ファイルをループして DB に保存する方法がわかりません。誰か例がありますか?

4

1 に答える 1

2

この目的でカスタム モデル バインダーを使用して、コントローラー ロジックが CSV 解析コードで混乱するのを避けることをお勧めします。

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()
);

これで、コントローラーを作成できます。

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>
}
于 2012-06-18T06:29:49.880 に答える