Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ASP.net MVC4 Multiselect ListBox with Many-to-Many relationship
- public class Employee
- {
- public int EmployeeId { get; set; }
- public String FirstName { get; set; }
- public String LastName { get; set; }
- public virtual ICollection<Division> Divisions { get; set; }
- }
- public class Division
- {
- public int DivisionId { get; set; }
- public String DivisionName { get; set; }
- public virtual ICollection<Employee> Employees { get; set; }
- }
- protected override void OnModelCreating(DbModelBuilder modelBuilder)
- {
- modelBuilder.Entity<Employee>()
- .HasMany(e => e.Divisions)
- .WithMany(d => d.Employees)
- .Map(m =>
- {
- m.ToTable("EmployeesDivisionsId");
- m.MapLeftKey("EmployeeId");
- m.MapRightKey("DivisionId");
- });
- }
- public ActionResult Index()
- {
- return View(db.Employees).ToList());
- }
- //
- // GET: /Employees/Details/5
- public ActionResult Details(int id = 0)
- {
- Employee employee = db.Employees.Find(id);
- if (employee == null)
- {
- return HttpNotFound();
- }
- return View(employee);
- }
- //
- // GET: /Employees/Create
- public ActionResult Create()
- {
- ViewBag.Divisions = new MultiSelectList(db.Divisions, "DivisionId", "DivisionName");
- return View();
- }
- //
- // POST: /Employees/Create
- [HttpPost]
- public ActionResult Create(Employee employee)
- {
- ViewBag.Divisions = new MultiSelectList(db.Divisions, "DivisionId", "DivisionName");
- if (ModelState.IsValid)
- {
- db.Employees.Add(employee);
- db.SaveChanges();
- return RedirectToAction("Index");
- }
- return View(employee);
- }
- <div class="editor-label">
- @Html.LabelFor(model => model.Divisions)
- </div>
- <div class="editor-field">
- @Html.ListBox("Divisions")
- @Html.ValidationMessageFor(model => model.Divisions)
- </div>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement