[HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Edit(int? id, byte[] rowVersion) { string[] fieldsToBind = new string[] { "Name", "Budget", "StartDate", "InstructorID", "RowVersion" }; if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var departmentToUpdate = await db.Departments.FindAsync(id); if (departmentToUpdate == null) { Department deletedDepartment = new Department(); TryUpdateModel(deletedDepartment, fieldsToBind); ModelState.AddModelError(string.Empty, "Unable to save changes, the department was deleted by another user"); ViewBag.InstructorID = new SelectList(db.Instructors, "ID", "FullName", deletedDepartment.InstructorID); return View(deletedDepartment); } if (TryUpdateModel(departmentToUpdate, fieldsToBind)) { try { db.Entry(departmentToUpdate).OriginalValues["RowVersion"] = rowVersion; await db.SaveChangesAsync(); return RedirectToAction("Index"); } catch (DbUpdateConcurrencyException ex) { var entry = ex.Entries.Single(); var clientValues = (Department)entry.Entity; var databaseEntry = entry.GetDatabaseValues(); if (databaseEntry == null) { ModelState.AddModelError(string.Empty, "无法保持更改,系已被其他用户删除"); } else { var databaseValues = (Department)databaseEntry.ToObject(); if (databaseValues.Name != clientValues.Name) { ModelState.AddModelError("Name", "当前值:" + databaseValues.Name); } if (databaseValues.Budget != clientValues.Budget) { ModelState.AddModelError("Budget", "当前值:" + databaseValues.Budget); } if (databaseValues.StartDate != clientValues.StartDate) { ModelState.AddModelError("StartDate", "当前值:" + databaseValues.StartDate); } if (databaseValues.InstructorID != clientValues.InstructorID) { ModelState.AddModelError("InstructorID", "当前值:" + db.Instructors.Find(databaseValues.InstructorID).FullName); } ModelState.AddModelError(string.Empty, "当前记录已经被其他人更改,如果你仍要保存这些数据,重新点击保持按钮或点击返回列表撤销本次操作"); departmentToUpdate.RowVersion = databaseValues.RowVersion; } } catch (RetryLimitExceededException) { ModelState.AddModelError(string.Empty, "无法保持更改"); } } ViewBag.InstructorID = new SelectList(db.Instructors, "ID", "FullName", departmentToUpdate.InstructorID); return View(departmentToUpdate); }