1

我正在寻找一种良好且易于使用的解决方案,用于在 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"])

希望我在正确的论坛上发布了这个!

4

0 回答 0