public async Task <IActionResult> Edit(Page page) // Model binding { if (ModelState.IsValid) { // Never bother Homepage page.Slug = page.Id == 1 ? "home" : page.Title.ToLower().Replace(' ', '-'); // Cannot change it to the same as other existed page var slug = await _context.Pages.Where(p => p.Id != page.Id).FirstOrDefaultAsync(p => p.Slug == page.Slug); if (slug != null) { ModelState.AddModelError("", "The page already exists"); return(View(page)); // re-fill the correct information } _context.Update(page); await _context.SaveChangesAsync(); TempData["Success"] = "The page has been updated!"; return(RedirectToAction("Edit", new { id = page.Id })); } return(View(page)); // re-fill the correct information }
public async Task <IActionResult> Edit(int id, Category category) { if (ModelState.IsValid) { category.Slug = category.Name.ToLower().Replace(" ", "-"); var cat = await _context.Categories.Where(c => c.Id != id).FirstOrDefaultAsync(c => c.Slug == category.Slug); if (cat != null) { ModelState.AddModelError("", "The category already exists!"); return(View(category)); } _context.Update(category); await _context.SaveChangesAsync(); TempData["Success"] = "The category has been edited."; //Actually here we only need id, but for generalization we use routeValues object return(RedirectToAction("Edit", new { id })); // GET /admin/categories/edit/id } return(View(category)); }