我正在使用捆绑包:ASP.NET MVC3、SQL Server 2012、EF5。当我尝试将值保存到我的数据库中时,我只能将 Book 的属性 IsSelected 保存在我的数据库中的 Books 表中,StudentName 无法保存,也无法将数据保存到数据库中的 StudentBooks 表中,其中包含 StudentId 和 BookId,多对的键-很多关系,有什么想法吗?
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; }
}