// Zwraca stronę o nazwie Upsert.cshtml public IActionResult Upsert(int?id) { ProduktVM produktVM = new ProduktVM() { Produkt = new Produkt(), ListaKategorii = _unitOfWork.Category.GetAll().Select(i => new SelectListItem { Text = i.Nazwa, Value = i.Id.ToString() }), ListaOkładek = _unitOfWork.Okladka.GetAll().Select(i => new SelectListItem { Text = i.Nazwa, Value = i.Id.ToString() }) }; if (id == null) { // jeśli brak id to otwórz stronę do tworzenia nowego wpisu return(View(produktVM)); } // jeżli jest id to oznacza, że otwórz stronę do edycji produktVM.Produkt = _unitOfWork.Produkt.Get(id.GetValueOrDefault()); if (produktVM.Produkt == null) { // nie znalazłem wpisu w bazie danych return(NotFound()); } return(View(produktVM)); }
public ActionResult Edit(int ID) { if (Session["rolle"] == null || (int)Session["rolle"] < Editor) { return(Redirect("/CMS/Produkt")); } ProduktVM produkt = new ProduktVM(); produkt.Produkter = pf.Get(ID); produkt.Kategorier = kf.GetAll(); return(View(produkt)); }
public IActionResult Upsert(ProduktVM produktVM) { if (ModelState.IsValid) { string webRootPath = _hostEnvironment.WebRootPath; var files = HttpContext.Request.Form.Files; if (files.Count > 0) { string fileName = Guid.NewGuid().ToString(); // W katalogu "wwwroot" var uploads = Path.Combine(webRootPath, @"images\produkty"); var extenstion = Path.GetExtension(files[0].FileName); if (produktVM.Produkt.ImageUrl != null) { // To jest dla edycji i musimy wykasować stare obrazy var imagePath = Path.Combine(webRootPath, produktVM.Produkt.ImageUrl.TrimStart('\\')); if (System.IO.File.Exists(imagePath)) { System.IO.File.Delete(imagePath); } } using (var filesStreams = new FileStream(Path.Combine(uploads, fileName + extenstion), FileMode.Create)) { files[0].CopyTo(filesStreams); } produktVM.Produkt.ImageUrl = @"\images\produkty\" + fileName + extenstion; } else { // aktualizacja kiedy nie zmieniamy obrazu if (produktVM.Produkt.Id != 0) { Produkt objFromDb = _unitOfWork.Produkt.Get(produktVM.Produkt.Id); produktVM.Produkt.ImageUrl = objFromDb.ImageUrl; } } if (produktVM.Produkt.Id == 0) { _unitOfWork.Produkt.Add(produktVM.Produkt); } else { _unitOfWork.Produkt.Update(produktVM.Produkt); } _unitOfWork.Save(); //return RedirectToAction("Index"); return(RedirectToAction(nameof(Index))); } else { produktVM.ListaKategorii = _unitOfWork.Category.GetAll().Select(i => new SelectListItem { Text = i.Nazwa, Value = i.Id.ToString() }); produktVM.ListaOkładek = _unitOfWork.Okladka.GetAll().Select(i => new SelectListItem { Text = i.Nazwa, Value = i.Id.ToString() }); if (produktVM.Produkt.Id != 0) { produktVM.Produkt = _unitOfWork.Produkt.Get(produktVM.Produkt.Id); } } return(View(produktVM)); }