public ActionResult Create(DataSubscriptions dataSubscriptions) { /** * 要注意的是:ModelState.IsValid的真假,是和model相关的,model中对属性的要求(非空、长度等等)必须和View中传过来一致 * 如果model中定义某个属性非空,但是在View中绑定的model中压根没有这个属性的值,ModelState.IsValid一定是为假的! * */ dataSubscriptions.BillCode = "9999999999"; dataSubscriptions.BillType = "0008"; dataSubscriptions.NextSendDate = DateTime.Now; if (ModelState.IsValid) { db.DataSubscriptions.Add(dataSubscriptions); db.SaveChanges(); HttpPostedFileBase file = Request.Files["file"]; if (file != null) { string fileName = Path.Combine(Request.MapPath("~/files/tmp"), Path.GetFileName(file.FileName)); file.SaveAs(fileName); using (ExcelPackage package = new ExcelPackage(new FileInfo(fileName))) { //注意!所有的起始位置都是1!所有的结束位置都是集合的元素长度值 ExcelWorksheet sheet = package.Workbook.Worksheets[1]; int colCount = sheet.Dimension.End.Column; int rowCount = sheet.Dimension.End.Row; for (ushort i = 2; i <= rowCount; i++) { BillStaffMapping mapping = new BillStaffMapping { BillType = dataSubscriptions.BillType, BillNumber = dataSubscriptions.BillCode, StaffNumber = sheet.GetValue(i,1).ToString(), //从外部Excel表格获取员工工号 TelPhone = sheet.GetValue(i,3).ToString(), Email = sheet.GetValue(i,4).ToString() }; db.BillStaffMappings.Add(mapping); db.SaveChanges(); } if (!System.IO.File.Exists(fileName)) System.IO.File.Delete(fileName); } } // this.UploadFile(Request["Receiver"]); return RedirectToAction("Index"); } return View(dataSubscriptions); }
public ActionResult Edit(DataSubscriptions dataSubscriptions) { if (ModelState.IsValid) { db.Entry(dataSubscriptions).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(dataSubscriptions); }