Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [HttpGet]
- public IActionResult Edit(int Id)
- {
- try
- {
- var employee = _context.Employees.SingleOrDefault(x => x.Id == Id);
- if (employee != null)
- {
- var employeeView = new EmployeeViewModel()
- {
- Id = employee.Id,
- FirstName = employee.FirstName,
- LastName = employee.LastName,
- DOB = employee.DOB,
- Email = employee.Email,
- Salary = employee.Salary
- };
- return View(employeeView);
- }
- else
- {
- TempData["errorMessage"] = $"Employee details not available with the Id: {Id}";
- return RedirectToAction("Index");
- }
- }
- catch (Exception ex)
- {
- TempData["errorMessage"] = ex.Message;
- return RedirectToAction("Index");
- }
- }
- [HttpPost]
- public IActionResult Edit(EmployeeViewModel? model, int Id)
- {
- try
- {
- if (ModelState.IsValid)
- {
- var employee = _context.Employees.SingleOrDefault(x => x.Id
- == Id);
- if (employee != null)
- {
- // Update employee properties with model data - that is what i wanted
- employee.Id = model.Id;
- employee.FirstName = model.FirstName;
- employee.LastName = model.LastName;
- employee.DOB = model.DOB;
- employee.Email = model.Email;
- employee.Salary = model.Salary;
- _context.Update(employee);
- _context.SaveChanges();
- TempData["successMessage"] = "Employee edited successfully!";
- return RedirectToAction("Index");
- }
- else
- {
- TempData["errorMessage"] = $"Employee with Id {employee.Id} not found";
- return RedirectToAction("Index");
- }
- }
- else
- {
- //my code always directs me to this Employee not found :/
- TempData["errorMessage"] = $"Employee not found";
- return View("Edit", model);
- }
- }
- catch (Exception ex)
- {
- TempData["errorMessage"] = ex.Message;
- return RedirectToAction("Index");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement