Пример #1
0
        public ActionResult Create(ProductViewModels sp)
        {
            try
            {
                var validImageTypes = new string[]
                {
                    "image/gif",
                    "image/jpeg",
                    "image/pjpeg",
                    "image/png"
                };

                if (sp.ImageUpload == null || sp.ImageUpload.ContentLength == 0)
                {
                    ModelState.AddModelError("ImageUpload", "Chưa chọn hình");
                }
                else if (!validImageTypes.Contains(sp.ImageUpload.ContentType))
                {
                    ModelState.AddModelError("ImageUpload", "Làm ơn chọn file có định dạng hình GIF, JPG, PNG.");
                }

                if (ModelState.IsValid)
                {
                    if (sp.ImageUpload != null && sp.ImageUpload.ContentLength > 0)
                    {
                        var uploadDir = "~/image/product";
                        var imagePath = Path.Combine(Server.MapPath(uploadDir), sp.ImageUpload.FileName);
                        var imageUrl  = Path.Combine(uploadDir, sp.ImageUpload.FileName);
                        sp.ImageUpload.SaveAs(imagePath);
                        sp.Hinh = sp.ImageUpload.FileName;
                    }
                }
                sp.NgayDangSP = DateTime.Now;
                sp.LuotXem    = 0;
                ProductBus.Them(sp);
                return(RedirectToAction("Index"));
            }
            catch (Exception ex)
            {
                ProductViewModels spham = new ProductViewModels();
                spham.dsLoai1 = LoaiBus.DanhSach();
                return(View(spham));
            }
        }
Пример #2
0
 public ActionResult Create(sanpham sp)
 {
     if (HttpContext.Request.Files.Count > 0)
     {
         var hpf = HttpContext.Request.Files[0];
         if (hpf.ContentLength > 0)
         {
             string filename             = Guid.NewGuid().ToString();
             string fullpathwithfilename = "/Images/chitietsanpham/" + filename + ".jpg";
             hpf.SaveAs(Server.MapPath(fullpathwithfilename));
             sp.HinhAnh = fullpathwithfilename;
         }
     }
     ProductBus.Them(sp);
     return(RedirectToAction("Index"));
     //}
     //catch
     //{
     //    return View();
     //}
 }