Advertisement
Guest User

z

a guest
Oct 10th, 2012
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ASP.net MVC4 Multiselect ListBox with Many-to-Many relationship
  2. public class Employee
  3. {
  4.     public int EmployeeId { get; set; }
  5.     public String FirstName { get; set; }
  6.     public String LastName { get; set; }
  7.  
  8.     public virtual ICollection<Division> Divisions { get; set; }
  9. }
  10.  
  11. public class Division
  12. {
  13.     public int DivisionId { get; set; }
  14.     public String DivisionName { get; set; }
  15.  
  16.     public virtual ICollection<Employee> Employees { get; set; }
  17. }
  18.    
  19. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  20.     {
  21.  
  22.         modelBuilder.Entity<Employee>()
  23.                 .HasMany(e => e.Divisions)
  24.                 .WithMany(d => d.Employees)
  25.                 .Map(m =>
  26.                 {
  27.                     m.ToTable("EmployeesDivisionsId");
  28.                     m.MapLeftKey("EmployeeId");
  29.                     m.MapRightKey("DivisionId");
  30.                 });      
  31.     }
  32.    
  33. public ActionResult Index()
  34.     {
  35.         return View(db.Employees).ToList());
  36.     }
  37.  
  38.     //
  39.     // GET: /Employees/Details/5
  40.  
  41.     public ActionResult Details(int id = 0)
  42.     {
  43.         Employee employee = db.Employees.Find(id);
  44.         if (employee == null)
  45.         {
  46.             return HttpNotFound();
  47.         }
  48.         return View(employee);
  49.     }
  50.  
  51.     //
  52.     // GET: /Employees/Create
  53.  
  54.     public ActionResult Create()
  55.     {
  56.         ViewBag.Divisions = new MultiSelectList(db.Divisions, "DivisionId", "DivisionName");
  57.  
  58.         return View();
  59.     }
  60.  
  61.     //
  62.     // POST: /Employees/Create
  63.  
  64.     [HttpPost]
  65.     public ActionResult Create(Employee employee)
  66.     {
  67.         ViewBag.Divisions = new MultiSelectList(db.Divisions, "DivisionId", "DivisionName");
  68.  
  69.         if (ModelState.IsValid)
  70.         {
  71.             db.Employees.Add(employee);
  72.             db.SaveChanges();
  73.             return RedirectToAction("Index");
  74.         }
  75.  
  76.         return View(employee);
  77.     }
  78.    
  79. <div class="editor-label">
  80.         @Html.LabelFor(model => model.Divisions)
  81.     </div>
  82.     <div class="editor-field">
  83.         @Html.ListBox("Divisions")
  84.         @Html.ValidationMessageFor(model => model.Divisions)
  85.     </div>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement