Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class FooViewModel
- {
- // other properties
- public int SelectedBarId { get; set; }
- public IEnumerable<SelectListItem> BarOptions { get; set; }
- }
- public ActionResult CreateFoo()
- {
- var model = new FooViewModel();
- PopulateBarOptions(model);
- return View(model);
- }
- [HttpPost]
- public ActionResult CreateFoo(FooViewModel model)
- {
- if (ModelState.IsValid)
- {
- var foo = new Foo
- {
- // map over other properties from model here
- Bar = db.Bars.Find(model.SelectedBarId)
- };
- db.Foos.Add(foo);
- db.SaveChanges();
- return RedirectToAction("Index");
- }
- PopulateBarOptions(model);
- return View(model);
- }
- protected void PopulateBarOptions(FooViewModel model)
- {
- model.BarOptions = db.Bars.Select(x => new SelectListItem { Value = x.Id.ToString(), Text = x.Name });
- }
- @Html.DropDownListFor(m => m.SelectedBarId, Model.BarOptions)
- Bars = db.Bars.Where(x => model.SelectedBarIds.Contains(x.Id))
- @Html.ListBoxFor(m => m.SelectedBarIds, Model.BarOptions)
- // remove deselected items
- foo.Bars.Where(x => !model.SelectedBarIds.Contains(x.Id)).ToList()
- .ForEach(x => foo.Bars.Remove(x));
- // add newly selected items
- var existingBarIds = foo.Bars.Select(x => x.Id);
- db.Bars.Where(x => model.SelectedBarIds.Exclude(existingBarIds).Contains(x.Id)).ToList()
- .ForEach(x => foo.Bars.Add(x));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement