我正在寻找一个好的且易于使用的解决方案,用于在MVC中为多对多关系创建MultiSelectLists。
我有以下示例代码并且它工作正常,但它只需要很多代码,如果它更短,更智能,甚至以某种方式制作通用它会很酷,这样在将来的项目中创建MultiSelectLists很容易..
以下是我的表现,(没什么好看的)
我的数据库首先使用实体框架代码: 书籍和作者,其中一本书可以有多位作者。
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; }
}
控制器
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);
}
查看
@Html.ListBox("SelectedBooks",(MultiSelectList)ViewData["BooksList"])
希望我在正确的论坛发布此内容!