I am new to ASP.net MVC and use viewmodel rather than viewbags to populate my dropdowns, as I have seen most people recommend against them. I have a slick UI that does cascading drop-down lists and autocomplete (not shown here), but I cannot get my data back to the database.
Models:
public partial class Car { public int CarID { get; set; } public string CarName { get; set; } public int ModelID { get; set; } public int ManufacturerID { get; set; } public int CarColorID { get; set; } public Nullable<decimal> Price { get; set; } public string Description { get; set; } public virtual CarColor CarColor { get; set; } public virtual Manufacturer Manufacturer { get; set; } public virtual CarModel CarModel { get; set; } } public partial class CarColor { public CarColor() { this.Cars = new HashSet<Car>(); } public int ColorID { get; set; } public string ColorName { get; set; } public virtual ICollection<Car> Cars { get; set; } } public partial class CarModel { public CarModel() { this.Cars = new HashSet<Car>(); } public int CarModelID { get; set; } public int ManufacturerID { get; set; } public string CarModelName { get; set; } public virtual ICollection<Car> Cars { get; set; } public virtual Manufacturer Manufacturer { get; set; } } public partial class Manufacturer { public Manufacturer() { this.Cars = new HashSet<Car>(); this.Manufacturer1 = new HashSet<Manufacturer>(); this.CarModels = new HashSet<CarModel>(); } public int ManufacturerID { get; set; } public string ManufacturerName { get; set; } public Nullable<int> ParentID { get; set; } public virtual ICollection<Car> Cars { get; set; } public virtual ICollection<Manufacturer> Manufacturer1 { get; set; } public virtual Manufacturer Manufacturer2 { get; set; } public virtual ICollection<CarModel> CarModels { get; set; } }
ViewModel:
public class AnotherTestViewModel { public Car car { get; set; } public IEnumerable<SelectListItem> CarModels { get; set; } public IEnumerable<SelectListItem> Manufacturers { get; set; } public IEnumerable<SelectListItem> CarColors { get; set; } }
Controller:
public ActionResult Create() { var model = new AnotherTestViewModel(); using (new CarTestEntities()) { model.CarModels = db.CarModels.ToList().Select(x => new SelectListItem { Value = x.CarModelID.ToString(), Text = x.CarModelName }); model.Manufacturers = db.Manufacturers.ToList().Select(x => new SelectListItem { Value = x.ManufacturerID.ToString(), Text = x.ManufacturerName }); model.CarColors = db.CarColors.ToList().Select(x => new SelectListItem { Value = x.ColorID.ToString(), Text = x.ColorName }); } return View(model); }
I saw several recommendations for using Automapper, because EntityState.Modified will not work, but I'm not sure how to configure it, because using the code below does not work.
Mapper.CreateMap<AnotherTestViewModel, Car>(); Mapper.CreateMap<Car, AnotherTestViewModel>(); var newCar = Mapper.Map<AnotherTestViewModel, Car>(model);
Any ideas?
Jim
source share