// GET: Principles/Edit/5 public async Task <IActionResult> Edit(int?id) { if (id == null) { return(NotFound()); } var principle = await _context.Principles.FindAsync(id); if (principle == null) { return(NotFound()); } // Must initialize var viewModel = new PrincipleEditViewModel() { Principle = principle, }; return(View(viewModel)); }
public async Task <IActionResult> Edit(int id, PrincipleEditViewModel viewModel) { var principle = viewModel.Principle; if (id != principle.PrincipleId) { return(NotFound()); } if (ModelState.IsValid) { try { if (ModelState.IsValid) { if (viewModel.PrincipleFileToSave != null) { // These are required to save the file to the project's wwwroot/Images folder. var uniqueFileName = GetUniqueFileName(viewModel.PrincipleFileToSave.FileName); var uploads = Path.Combine(_hostEnviro.WebRootPath, "Images"); var filePath = Path.Combine(uploads, uniqueFileName); // Creating a formatted string to save to the Db. var imagepath = "~/Images/" + uniqueFileName; // Assign that variable to PrincipleImage. // Must drill down through the "model" parameter passed in here. viewModel.Principle.PrincipleImage = imagepath; viewModel.PrincipleFileToSave.CopyTo(new FileStream(filePath, FileMode.Create)); // Based on the debugger, the file is added to the Images folder here. } else { principle = await _context.Principles.FindAsync(id); var formerFileName = principle.PrincipleImage.Substring(2); viewModel.Principle.PrincipleImage = formerFileName; // Update all properties of viewModel.Principle with the principle we got from the Db. // Except for the PrincipleImage property and the PrincipleId principle.PrincipleName = viewModel.Principle.PrincipleName; principle.PrincipleDescription = viewModel.Principle.PrincipleDescription; principle.User = viewModel.Principle.User; principle.UserId = viewModel.Principle.UserId; viewModel.Principle = principle; } // Identity. Need this outside the if statements to pick up the UserId no matter the condition. var User = await GetCurrentUserAsync(); viewModel.Principle.UserId = User.Id; // Data passed to Db. _context.Update(viewModel.Principle); await _context.SaveChangesAsync(); // Redirect to the Details view of the newly created principle. return(RedirectToAction("Details", new { id = viewModel.Principle.PrincipleId })); } } catch (DbUpdateConcurrencyException) { if (!PrincipleExists(principle.PrincipleId)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(viewModel)); }