I'm looking for a good and easy to use solution for creating MultiSelectLists in MVC for many to many relationships.
I have this following example code and it works fine, but it just takes a lot of code, it would be cool if it where shorter, smarter, or even made generic somehow, so that it's easy to create MultiSelectLists in future projects..
Here is how i've done it, (Nothing fancy)
My Database using Entity Framework Code First: Books, and authors, where one book, can have multiple authors.
public class DataContext : DbContext
{
public DbSet<Book> Books { get; set; }
public DbSet<Author> Authors { get; set; }
}
public class Book
{
public int Id { get; set; }
public string Name { get; set; }
//Allows multiple authors for one book.
public virtual ICollection<Author> Authors { get; set; }
}
public class Author
{
public int Id { get; set; }
public string Name { get; set; }
[NotMapped]
public int[] SelectedBooks { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
Controller
public ActionResult Edit(int id = 0)
{
Author author = db.Authors.Find(id);
if (author == null)
{
return HttpNotFound();
}
ViewData["BooksList"] = new MultiSelectList(db.Books, "Id", "Name", author.Books.Select(x => x.Id).ToArray());
return View(author);
}
[HttpPost]
public ActionResult Edit(Author author)
{
ViewData["BooksList"] = new MultiSelectList(db.Books, "Id", "Name", author.SelectedBooks);
if (ModelState.IsValid)
{
//Update all the other values.
Author edit = db.Authors.Find(author.Id);
edit.Name = auther.Name;
//------------
//Make adding items possible
if (edit.Books == null) edit.Books = new List<Book>();
//Remove the old, add the new, instead of finding out what to remove, and what to add, and what to leave be.
foreach (var item in edit.Books.ToList())
{
edit.Books.Remove(item);
}
foreach (var item in author.SelectedBooks)
{
edit.Books.Add(db.Books.Find(item));
}
//-------------
// This is the code i want to simplify
// Would be cool with a generic extention method like this:
// db.ParseNewEntities(edit.Books, author.SelectedBooks);
// I just don't know how to code it.
db.SaveChanges();
return RedirectToAction("Index");
}
return View(author);
}
View
@Html.ListBox("SelectedBooks",(MultiSelectList)ViewData["BooksList"])
Hope i posted this in the right forum!
Authershould beAuthor. – codesparkle♦ Nov 11 '12 at 19:22