// GET: Admin/SanPhams/Edit/5 public async Task <IActionResult> Edit(string id) { if (id == null) { return(NotFound()); } var sanPham = await _context.SanPham.FirstOrDefaultAsync(x => x.MaSp.Contains(id)); if (sanPham == null) { return(NotFound()); } SanPhamModelView sp = new SanPhamModelView() { MaSp = sanPham.MaSp, TenSp = sanPham.TenSp, LoaiSp = sanPham.LoaiSp, ThuongHieu = sanPham.ThuongHieu, MoTa = sanPham.MoTa, SoLuongCon = sanPham.SoLuongCon, DonGia = sanPham.DonGia, }; ViewData["LoaiSp"] = new SelectList(_context.LoaiSp, "MaLoai", "MaLoai", sanPham.LoaiSp); return(View(sp)); }
public async Task <IActionResult> Edit(string id, [Bind("MaSp,TenSp,LoaiSp,ThuongHieu,DonGia,SoLuongCon,MoTa,HinhAnh")] SanPhamModelView sanPham) { if (!sanPham.MaSp.Contains(id)) { return(NotFound()); } var sp = await _context.SanPham.FirstOrDefaultAsync(x => x.MaSp.Contains(id)); if (ModelState.IsValid) { string wwwRootPath = _hostEnvironment.WebRootPath; if (sanPham.HinhAnh != null) { string fileName = Guid.NewGuid().ToString(); var uploads = Path.Combine(wwwRootPath, @"image\"); var extension = Path.GetExtension(sanPham.HinhAnh.FileName); if (sp.HinhAnh != null) { var imagePath = Path.Combine(wwwRootPath, sp.HinhAnh.TrimStart('\\')); if (System.IO.File.Exists(imagePath)) { System.IO.File.Delete(imagePath); } } using (var filesStreams = new FileStream(Path.Combine(uploads, fileName + extension), FileMode.Create)) { sanPham.HinhAnh.CopyTo(filesStreams); } sp.HinhAnh = @"\image\" + fileName + extension; } try { sp.DonGia = sanPham.DonGia; sp.SoLuongCon = sanPham.SoLuongCon; sp.MoTa = sanPham.MoTa; _context.Update(sp); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!SanPhamExists(sanPham.MaSp)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["LoaiSp"] = new SelectList(_context.LoaiSp, "MaLoai", "MaLoai", sanPham.LoaiSp); return(View(sanPham)); }
public async Task <IActionResult> Create([Bind("MaSp,TenSp,LoaiSp,ThuongHieu,DonGia,SoLuongCon,MoTa,HinhAnh")] SanPhamModelView sanPham) { if (ModelState.IsValid) { SanPham sp = new SanPham() { MaSp = sanPham.MaSp, TenSp = sanPham.TenSp, LoaiSp = sanPham.LoaiSp, ThuongHieu = sanPham.ThuongHieu, MoTa = sanPham.MoTa, HinhAnh = "", }; string wwwRootPath = _hostEnvironment.WebRootPath; if (sanPham.HinhAnh != null) { string fileName = Guid.NewGuid().ToString(); var uploads = Path.Combine(wwwRootPath, @"Image\"); var extension = Path.GetExtension(sanPham.HinhAnh.FileName); using (var filesStreams = new FileStream(Path.Combine(uploads, fileName + extension), FileMode.Create)) { sanPham.HinhAnh.CopyTo(filesStreams); } sp.HinhAnh = @"\image\" + fileName + extension; } sp.DonGia = 0; sp.SoLuongCon = 0; _context.Add(sp); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["LoaiSp"] = new SelectList(_context.LoaiSp, "MaLoai", "MaLoai", sanPham.LoaiSp); return(View(sanPham)); }