Advertisement
Guest User

Untitled

a guest
Mar 24th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 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)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement