public ActionResult Insert(CarBrand brand) { BrandViewModel bmv; if (ModelState.IsValid) { using (ApplicationDbContext db = new ApplicationDbContext()) { db.CarBrands.Add(brand); db.SaveChanges(); bmv = ViewModelFactory.CreateBrandViewModel(brand, "ReadOnly"); } } else { bmv = ViewModelFactory.CreateBrandViewModel(null, "WriteOnly"); } return View("Index", bmv); }
public ActionResult Update(CarBrand brand) { BrandViewModel bmv; string displayMode = ""; if (ModelState.IsValid) { using(ApplicationDbContext db = new ApplicationDbContext()) { CarBrand existing = db.CarBrands.Find(brand.CarBrandId); existing.BrandName = brand.BrandName; db.SaveChanges(); } } else { displayMode = "ReadWrite"; } bmv = ViewModelFactory.CreateBrandViewModel(brand, displayMode); return View("index", bmv); }
//public static CarViewModel CreateCarViewModel(Car car) //{ // ApplicationDbContext db = new ApplicationDbContext(); // CarViewModel ecvm = new CarViewModel(); // ecvm.CarData = car; // ecvm.Branches = new SelectList(db.Branches, "BranchId", "BranchName", car.BranchId); // ecvm.CarTypes = new SelectList(db.CarTypes, "CarTypeId", "Description", car.CarTypeId); // return ecvm; //} //public static CarViewModel CreateCarViewModel(int? id) //{ // ApplicationDbContext db = new ApplicationDbContext(); // Car car = db.Cars.Find(id); // if (car != null) // { // //There is some code that is executed twice, but it's worth considering we abide by the DRY principle // return CreateCarViewModel(car); // } // return null; //todo return an error or make View return an error //} //public static CarViewModel CreateCarViewModel() //{ // return CreateCarViewModel(new Car()); //} #endregion //#region SearchCarViewModel //public static SearchCarViewModel CreateSearchCarViewModel(Car car) //{ // CarRentalContext db = new CarRentalContext(); // SearchCarViewModel scvm = new SearchCarViewModel(); // CarType carType; // Branch branch; // scvm.CarData = car; // carType = db.CarTypes.Find(car.CarTypeId); // //if (carType != null) // // scvm.CarCode = carType.CarCode; // //else // // scvm.CarCode = ""; // //branch = db.Branches.Find(car.BranchId); // //if (branch != null) // //{ // // scvm.Branch = branch.City + " - " + branch.BranchName; // //} // return scvm; //} //public static SearchCarViewModel CreateSearchCarViewModel() //{ // return CreateSearchCarViewModel(new Car()); //} //#endregion #region BrandViewModel Experimental public static BrandViewModel CreateBrandViewModel(CarBrand brand, string displayMode) { BrandViewModel model = new BrandViewModel(); model.DisplayMode = displayMode; using (ApplicationDbContext db = new ApplicationDbContext()) { model.Brands = db.CarBrands.ToList(); model.SelectedBrand = brand; } return model; }