Exemplo n.º 1
0
        public ActionResult Create([Bind(Include = "ProductId,Title,Description,Text,Visit,Price,ImageName,Sort")] Product product,
                                   List <int> selectedCategory, HttpPostedFileBase imageProduct, string tags)
        {
            if (ModelState.IsValid)
            {
                // Check Categories
                if (selectedCategory == null)
                {
                    ViewBag.Category   = true;
                    ViewBag.Categories = _categoryBusiness.Get();
                    return(View(product));
                }
                // Image
                product.ImageName = "user123456789.png";
                if (imageProduct != null && imageProduct.IsImage())
                {
                    product.ImageName = Guid.NewGuid().ToString() + Path.GetExtension(imageProduct.FileName);
                    imageProduct.SaveAs(Server.MapPath("/Content/Image/Product/" + product.ImageName));
                    ImageResizer img = new ImageResizer();
                    img.Resize(Server.MapPath("/Content/Image/Product/" + product.ImageName),
                               Server.MapPath("/Content/Image/Product/Thumbnail/" + product.ImageName));
                }

                _productBusiness.Insert(product);
                _productBusiness.Save();

                // Category
                foreach (var category in selectedCategory)
                {
                    _productCategoryBusiness.Insert(new ProductCategory()
                    {
                        CategoryId = category,
                        ProductId  = product.ProductId
                    });
                }

                // Tags
                if (!string.IsNullOrEmpty(tags))
                {
                    string[] tagsList = tags.Split(',');
                    foreach (var tag in tagsList)
                    {
                        _tagBusiness.Insert(new Tag()
                        {
                            ProductId = product.ProductId,
                            TagName   = tag.Trim()
                        });
                    }
                }
                _tagBusiness.Save();
                _productCategoryBusiness.Save();

                return(RedirectToAction("Index"));
            }
            ViewBag.Categories = _categoryBusiness.Get();
            return(View(product));
        }