public async Task <IActionResult> Create(Page page) // Model binding { if (ModelState.IsValid) { page.Slug = page.Title.ToLower().Replace(' ', '-'); page.Sorting = 100; var slug = await _context.Pages.FirstOrDefaultAsync(p => p.Slug == page.Slug); if (slug != null) { ModelState.AddModelError("", "The title already exists"); return(View(page)); // re-fill the correct information } _context.Add(page); await _context.SaveChangesAsync(); TempData["Success"] = "The page has been added!"; return(RedirectToAction("Index")); } return(View(page)); // re-fill the correct information }
public async Task <IActionResult> Create(Category category) { if (ModelState.IsValid) { category.Slug = category.Name.ToLower().Replace(" ", "-"); category.Sorting = 100; var slug = await _context.Categories.FirstOrDefaultAsync(c => c.Slug == category.Slug); if (slug != null) { //immediately give an error feedback to front end ModelState.AddModelError("", "The category already exists"); return(View(category)); // re-fill the correct information } _context.Add(category); await _context.SaveChangesAsync(); TempData["Success"] = "The category has been added!"; return(RedirectToAction("Index")); } return(View(category)); }
public async Task <IActionResult> Create(Product product) { ViewBag.CategoryId = new SelectList(_context.Categories.OrderBy(c => c.Sorting), "Id", "Name"); if (ModelState.IsValid) { product.Slug = product.Name.ToLower().Replace(" ", "-"); var prod = await _context.Products.FirstOrDefaultAsync(p => p.Slug == product.Slug); if (prod != null) { ModelState.AddModelError("", "The product already exists"); return(View(product)); } // Find it from internet or somewhere else and create dir wwwroot/media/products // Then copy/paste it to the dir. It's a default in case no image is uploaded. string imageName = "noimage.png"; if (product.ImageUpload != null) { string uploadsDir = Path.Combine(_webHostEnvironment.WebRootPath, "media/products"); imageName = Guid.NewGuid().ToString() + "_" + product.ImageUpload.FileName; string filePath = Path.Combine(uploadsDir, imageName); using (FileStream fs = new FileStream(filePath, FileMode.Create)) { await product.ImageUpload.CopyToAsync(fs); } } product.Image = imageName; _context.Add(product); await _context.SaveChangesAsync(); TempData["Success"] = "The product has been added."; return(RedirectToAction("Index")); } return(View(product)); }