コード例 #1
0
        public ActionResult Upload(BarsUploadViewModel viewmodel)
        {
            if (ModelState.IsValid) // validate file exist
            {
                if (viewmodel.ExcelFile != null && viewmodel.ExcelFile.ContentLength > 0)
                {
                    var        fileName      = Path.GetFileName(viewmodel.ExcelFile.FileName);
                    var        path          = Path.Combine(Server.MapPath("~/Uploads/Bars/"), DateTime.Now.GetTimeStamp() + "_" + fileName);
                    List <Bar> addedEntities = new List <Bar>();
                    viewmodel.ExcelFile.SaveAs(path); // save a copy of the uploaded file.
                    // convert the uploaded file into datatable, then add/update db entities.
                    var dtBarsHours = ImportUtils.ImportXlsxToDataTable(viewmodel.ExcelFile.InputStream, true, 1);
                    var excelData   = dtBarsHours.AsEnumerable().Select(row => new BarUploadEntity()
                    {
                        Year           = int.Parse(row["Year"].ToString()),
                        BarNumber      = row["State BARS Number"].ToString(),
                        MapToBarNumber = row["Map to"].ToString(),
                        DisplayName    = row["Display Name"].ToString(),
                        Period         = string.IsNullOrWhiteSpace(row["Period"].ToString()) ? (int?)null : int.Parse(row["Period"].ToString()),
                        IsActive       = string.IsNullOrWhiteSpace(row["Is Active"].ToString()) ? false : row["Is Active"].ToString() == "1" ? true : false
                    }).ToList();
                    excelData = excelData.GroupBy(x => x.BarNumber).Select(y => y.First()).ToList();

                    int numOfAddedEntities = 0, numOfUpdatedEntities = 0;
                    _barService.UploadBars(viewmodel.BarsYear.Value, excelData, out numOfAddedEntities, out numOfUpdatedEntities);

                    Success($"<strong>{numOfAddedEntities}</strong> records have been successfully added. <br\\>"
                            + $"<strong>{numOfUpdatedEntities}</strong> records have been successfully updated.");
                }
            }

            return(RedirectToAction("Index", new
            {
                year = viewmodel.BarsYear.Value
            }));
        }
コード例 #2
0
        public ActionResult Upload()
        {
            var viewmodel = new BarsUploadViewModel();

            return(View(viewmodel));
        }