Example #1
0
        public async Task <ActionResult> DeleteAddProduct([Bind(Include = "ID,categories")] AddProducts category)
        {
            var product = db.Products.Include(m => m.Categories).First(m => m.ProductId == category.ID);

            if (!ModelState.IsValid)
            {
                TempData["product"] = product;
                return(View(category));
            }

            foreach (int index in category.categories)
            {
                product.Categories.Remove(product.Categories.Find(m => m.CategoryID == index));
            }


            db.Entry(product).State = EntityState.Modified;
            await db.SaveChangesAsync();

            return(RedirectToAction("Index", "Products"));
        }
Example #2
0
        public async Task <ActionResult> AddProducts([Bind(Include = "ID,categories")] AddProducts category)
        {
            ViewData["ProductId"] = new SelectList(items: db.Products, dataValueField: "ProductId", dataTextField: "ProductName");
            if (!ModelState.IsValid)
            {
                return(View(category));
            }


            var categories = (Dictionary <int, Category>)Session["categories"];
            var product    = await db.Products.FindAsync(category.ID);

            if (product.Categories == null)
            {
                product.Categories = new List <Category>();
            }


            foreach (int index in category.categories)
            {
                Category output = null;
                categories.TryGetValue(index, out output);
                db.Categories.Attach(output);
                if (product.Categories.Contains(output) == false)
                {
                    product.Categories.Add(output);
                }
            }

            Session.Remove("products");
            Session.Remove("categories");
            db.Entry(product).State = EntityState.Modified;
            await db.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }