Exemplo n.º 1
0
        // GET: MB
        public ActionResult Index()
        {
            var data = new NewProductVM()
            {
                Price = 100,
                ProductName = "Hoodie"
            };

            ViewData["MyName"] = "Will";
            ViewData["MyTitle"] = "ASP .NET MVC 1";
            ViewBag.Title = "ASP .NET MVC 2";

            ViewBag.Prodcuts = db.Products.Take(5).ToList();
            TempData["msg"] = "Test";
            ViewData.Model = data;

            return View();
        }
        public ActionResult NewProduct(NewProductVM product)
        {
            if (ModelState.IsValid)
            {
                var prod = new Product();
                prod.ProductName = product.ProductName;
                prod.Price = product.Price;
                prod.Stock = 1;
                prod.Active = true;

                //db.Products.Add(prod);
                ///** Use Repository **///
                repo.Add(prod);

                try
                {
                    //db.SaveChanges();
                    ///** Use Repository **///
                    repo.UnitOfWork.Commit();

                    return RedirectToAction("Index");
                }
                catch (DbEntityValidationException ex)
                {
                    var allErrors = new List<string>();

                    foreach (DbEntityValidationResult re in ex.EntityValidationErrors)
                    {
                        foreach (DbValidationError err in re.ValidationErrors)
                        {
                            allErrors.Add(err.ErrorMessage);
                        }
                    }

                    ViewBag.Errors = allErrors;
                }
            }

            return View();
        }