public async Task <IActionResult> Create(Page page) { //check if model is valid if (ModelState.IsValid) { //set the page prop page.Slug = page.Title.ToLower().Replace(" ", "-"); page.Sorting = 100; //get the slug which is equal to current var slug = await context.Pages.FirstOrDefaultAsync(x => x.Slug == page.Slug); if (slug != null) { ModelState.AddModelError("", "The page allready exists"); return(View(page)); } //add the page to db context.Add(page); await context.SaveChangesAsync(); TempData["Success"] = "The page has been added!"; return(RedirectToAction("Index")); } return(View(page)); }
public async Task <IActionResult> Create(Product product) { ViewBag.CategoryId = new SelectList(context.Categories.OrderBy(x => x.Sorting), "Id", "Name"); //check if model is valid if (ModelState.IsValid) { //set the page prop product.Slug = product.Name.ToLower().Replace(" ", "-"); //get the slug which is equal to current var slug = await context.Products.FirstOrDefaultAsync(x => x.Slug == product.Slug); if (slug != null) { ModelState.AddModelError("", "The product allready exists"); return(View(product)); } //add the image file string imageName = "noimage.png"; if (product.ImageUpload != null) { //set the directory using webHostEnvironment string uploadsDir = Path.Combine(webHostEnvironment.WebRootPath, "media/products"); //set the name of the image to be unique imageName = Guid.NewGuid().ToString() + "_" + product.ImageUpload.FileName; //set the full image path string filePath = Path.Combine(uploadsDir, imageName); //upload using FileStream class FileStream fs = new FileStream(filePath, FileMode.Create); await product.ImageUpload.CopyToAsync(fs); fs.Close(); } //set the property name product.Image = imageName; //add the page to db context.Add(product); await context.SaveChangesAsync(); TempData["Success"] = "The product has been added!"; return(RedirectToAction("Index")); } return(View(product)); }