我使用的捆綁包:ASP.NET MVC3,SQL Server 2012,EF5。當我嘗試將值保存到數據庫中時,我只能保存Book的屬性IsSelected in Books表中的數據庫,StudentName不能保存,並且不能將數據保存到數據庫中的StudentBooks表中,其中包含StudentId和BookId,多少關係,任何想法?ASP.NET MVC3創建多對多
public class CheckboxController : Controller
{
EFDbContext context = new EFDbContext(ConfigurationManager.ConnectionStrings[1].ConnectionString);
//
//GET: /Checkbox/
public ActionResult Index()
{
ViewModelData vmd = new ViewModelData();
List<Book> bookList = new List<Book>();
using (EFDbContext te = new EFDbContext(ConfigurationManager.ConnectionStrings[1].ConnectionString))
{
var student = te.Students.First();
vmd.StudentName = student.StudentName;
var data = te.Books.ToList();
foreach (var d in data) {
Book book = new Book();
book.BookName = d.BookName;
book.IsSelected = false;
book.BookId = d.BookId;
bookList.Add(book);
}
}
vmd.Books = bookList;
return View(vmd);
}
//
//GET: /Checkbox/
[HttpPost]
public ActionResult Index(ViewModelData vm)
{
foreach (var book in vm.Books) {
context.Books.First(x => x.BookId == book.BookId).IsSelected = book.IsSelected;
}
context.SaveChanges();
return View(vm);
}
}
public class ViewModelData
{
public string StudentName { get; set; }
public List<Book> Books { get; set; }
}
查看
@model UsingEFNew.Controllers.ViewModelData
@{
ViewBag.Title = "Example";
}
@using (Html.BeginForm("Index", "Checkbox", null, FormMethod.Post))
{
<div>Your Name:</div>
<div>
@Html.TextBoxFor(model => model.StudentName)
</div>
for (int i = 0; i < Model.Books.Count; i++) {
@Html.CheckBoxFor(m => Model.Books[i].IsSelected)
@Html.DisplayFor(m => Model.Books[i].BookName)
@Html.HiddenFor(m => Model.Books[i].BookId)
@Html.HiddenFor(m => Model.Books[i].BookName)
@:</br>
}
}
我的模型
public class Book {
public int BookId { get; set; }
public string BookName { get; set; }
public bool IsSelected { get; set; }
public ICollection<Student> Students { get; set; }
}
public class Student {
public int StudentId { get; set; }
public string StudentName { get; set; }
public ICollection<Book> Books { get; set; }
public ICollection<City> Cities { get; set; }
}
讓我看看你的書籍模型和你的學生模型 – Greg
完成,有什麼想法嗎? – Rakstit
這裏有很多問題。首先,你的ViewModel應該使用一個Student對象,而不僅僅是名字。其次,您在視圖中迭代集合的方式不正確,這就是綁定不正確的原因。給我你的項目,我會修復它。 – Greg