Exemple #1
0
        public ActionResult Index()
        {
            ViewData["MyTitle2"] = "ggggggggg2";

            var data = db.Product.Take(5).ToList();
            ViewBag.data = data;
            var data2 = new 新增產品ViewModel() {
                 Price=100,
                  ProductName="uuuuuuu"
            };
            return View(data2);
        }
        public ActionResult 新增產品ViewModel(新增產品ViewModel product)
        {
            //驗證model是否正確
            if (ModelState.IsValid)
            {
                //透過Valueinjecter新增相同名稱欄位
                var prod = Mapper.Map<Product>(product);
                //新增一個Table物件,寫入資料後透過EntityFramework寫回DB
                //var prod = new Product();
                ////prod.ProductName = product.productName;
                ////prod.Price = product.productPrice;
                prod.Stock = 1;//必要欄位還是要資料
                prod.Active = true;
                //db.Product.Add(prod);
                repo.Add(prod);
                //追蹤一個或多個驗證實體的失敗的程式碼
                try
                {
                    //db.SaveChanges();//確認資料表更動
                    repo.UnitOfWork.Commit();
                }
                catch (DbEntityValidationException ex)
                {
                    var allErrors = new List<string>();

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

                    return Content(string.Join("<br/>", allErrors));
                }

                //錯誤時導回index
                return RedirectToAction("index");
            }
            return View(product);
        }