Advertisement
Guest User

Untitled

a guest
Mar 24th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. public class FooViewModel
  2. {
  3. // other properties
  4.  
  5. public int SelectedBarId { get; set; }
  6.  
  7. public IEnumerable<SelectListItem> BarOptions { get; set; }
  8. }
  9.  
  10. public ActionResult CreateFoo()
  11. {
  12. var model = new FooViewModel();
  13.  
  14. PopulateBarOptions(model);
  15. return View(model);
  16. }
  17.  
  18. [HttpPost]
  19. public ActionResult CreateFoo(FooViewModel model)
  20. {
  21. if (ModelState.IsValid)
  22. {
  23. var foo = new Foo
  24. {
  25. // map over other properties from model here
  26. Bar = db.Bars.Find(model.SelectedBarId)
  27. };
  28. db.Foos.Add(foo);
  29. db.SaveChanges();
  30. return RedirectToAction("Index");
  31. }
  32.  
  33. PopulateBarOptions(model);
  34. return View(model);
  35. }
  36.  
  37. protected void PopulateBarOptions(FooViewModel model)
  38. {
  39. model.BarOptions = db.Bars.Select(x => new SelectListItem { Value = x.Id.ToString(), Text = x.Name });
  40. }
  41.  
  42. @Html.DropDownListFor(m => m.SelectedBarId, Model.BarOptions)
  43.  
  44. Bars = db.Bars.Where(x => model.SelectedBarIds.Contains(x.Id))
  45.  
  46. @Html.ListBoxFor(m => m.SelectedBarIds, Model.BarOptions)
  47.  
  48. // remove deselected items
  49. foo.Bars.Where(x => !model.SelectedBarIds.Contains(x.Id)).ToList()
  50. .ForEach(x => foo.Bars.Remove(x));
  51.  
  52. // add newly selected items
  53. var existingBarIds = foo.Bars.Select(x => x.Id);
  54. db.Bars.Where(x => model.SelectedBarIds.Exclude(existingBarIds).Contains(x.Id)).ToList()
  55. .ForEach(x => foo.Bars.Add(x));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement