I'm use bundle of: ASP.NET MVC3, SQL Server 2012, EF5. When I try to save values into my database, I can save only Book's property IsSelected in Books table in my database, StudentName cant saved, and cant saved datas into my StudentBooks table in database, whach contains StudentId and BookId, keys for many-to-many relationships, any ideas?
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; }
}
View
@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>
}
}
My Models
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; }
}