c# – 使用ASP.NET MVC 3的CSVHelper
发布时间:2020-12-15 17:26:54 所属栏目:百科 来源:网络整理
导读:我正在尝试上传一个csv文件并使用MVC3实现CSVHelper. https://github.com/JoshClose/CsvHelper 我还没有找到一个使用文件上传的例子.基本上,我需要获取CSV文件并映射到实体对象并保存到数据库.这是我的实体: public class SurveyEmailListModels { [Key] pu
我正在尝试上传一个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文件并保存到数据库.有人有例子吗? 解决方法
为了这个目的,我建议您使用自定义模型绑定器,以避免使用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> } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |