【问题标题】:CSVHelper with ASP.NET MVC 3CSVHelper 与 ASP.NET MVC 3
【发布时间】:2012-06-18 03:22:16
【问题描述】:

我正在尝试上传 csv 文件并使用 MVC3 实现 CSVHelper 主管。

https://github.com/JoshClose/CsvHelper

我还没有找到将其与文件上传一起使用的示例。基本上,我需要获取 CSV 文件并映射到实体对象并保存到数据库。这是我的实体:

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 文件并保存到数据库。有人举个例子吗?

【问题讨论】:

    标签: c# asp.net asp.net-mvc-3 entity-framework csv


    【解决方案1】:

    我建议您为此使用自定义模型绑定器,以避免 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>
    }
    

    【讨论】:

    • 嗨达林,感谢您的回复。我正在尝试实施您的解决方案,但在调试器中看不到 CSV 值。我在“return csvReader.GetRecords”上设置了一个断点,但没有看到任何值。如果我查看“CSVReader”本地变量,我会看到“+ CurrentRecord 'csvReader.CurrentRecord' 引发了类型为 'CsvHelper.CsvReaderException' string[] {CsvHelper.CsvReaderException} 的异常”
    • 如果您在控制器操作中放置断点并检查模型变量,您将看到结果。或者在返回检查之前简单地在模型绑定器中使用一个临时变量。还要确保您已阅读 CsvHelpers 文档以了解正确用法和预期格式。例如,您的 SurveyEmailListId 属性未使用可能导致错误的 [CsvField(Ignore = true)] 属性进行修饰。如果您在使用 CsvHelpers 时遇到问题,请提出一个新问题,因为这与 ASP.NET MVC 无关。
    • 好的,我在这里开始了一个新问题:stackoverflow.com/questions/11086942/…
    • 这个呢?您对 ASP.NET MVC 部分还有疑问吗?
    • 我现在可以在调试器控制台中看到 csv 文件的值,但是当“model”变量到达控制器时,它没有显示任何内容。它不应该将值数组传递给控制器​​吗?
    猜你喜欢
    • 1970-01-01
    • 2011-06-24
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    • 2012-06-23
    相关资源
    最近更新 更多