// GET: Storages/Create public ActionResult Create() { List <SelectListItem> goods = new List <SelectListItem>(); foreach (GoodInfo good in db.GoodInfoes) { goods.Add(new SelectListItem { Text = good.Name, Value = good.Id.ToString() }); } NewStorageGoodViewModel newStorage = new NewStorageGoodViewModel { Quantity = 0, Cost = 0, AllGoods = goods, }; return(View(newStorage)); }
public async Task <ActionResult> Create([Bind(Include = "SelectedGoodID,Cost,Quantity")] NewStorageGoodViewModel newstorage) { if (Session["CurrentUserID"] == null) { RedirectToAction("Login", "Home"); } int CurrentUserID = (int)Session["CurrentUserID"]; int goodID = newstorage.SelectedGoodID; double cost = newstorage.Cost; int quantity = newstorage.Quantity; Storage existingitem = await db.Storages.Where(d => d.GoodID == goodID && d.Cost == cost && d.UserID == CurrentUserID).FirstOrDefaultAsync(); //update exising one if (existingitem != null) { existingitem.Quantity = existingitem.Quantity + quantity; db.Entry(existingitem).State = EntityState.Modified; await db.SaveChangesAsync(); } else { //create new Storage newitem = new Storage { UserID = CurrentUserID, GoodID = goodID, Cost = cost, Quantity = quantity, TotalCost = cost * quantity }; if (ModelState.IsValid) { db.Storages.Add(newitem); await db.SaveChangesAsync(); } } return(RedirectToAction("Index")); }