예제 #1
0
        public async Task <IActionResult> Create([Bind("ProductId,Name,Description,Price,Photo,CategoryId")] Product product)
        {
            if (ModelState.IsValid)
            {
                // get the image
                var files = HttpContext.Request.Form.Files;

                if (files != null)
                {
                    string uploadFolder = Path.Combine(_hostingEnvironment.WebRootPath, @"img");
                    // create an unique file name using guid and the file
                    string uniqueFileName = Guid.NewGuid().ToString() + files[0].FileName;
                    string filePath       = Path.Combine(uploadFolder, uniqueFileName);

                    using (var fileStream = new FileStream(filePath, FileMode.Create))
                    {
                        await files[0].CopyToAsync(fileStream);
                        product.Photo = uniqueFileName;
                    }
                }


                _context.Add(product);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["CategoryId"] = new SelectList(_context.Category, "CategoryId", "Name", product.CategoryId);
            return(View(product));
        }
예제 #2
0
        public async Task <IActionResult> Create([Bind("CategoryId,Name")] Category category)
        {
            if (ModelState.IsValid)
            {
                _context.Add(category);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(category));
        }