0

I'm using MVC 5, EntityFramwork 6, Code first approach

I see a lot of example in using checkbox in entity framework, but I didn't see any case like what I need.

I will use this simple case:

I have two simple Course and Student, Every Course has many Students. Every Student has many Courses.

In EF models:

Course class is

public class Course
{
    public int ID { get; set; }
    public string Title { get; set; }
    public List<Student> Students { get; set; }
}

and Student class is

public class Student
{
    public int ID { get; set; }
    public string Name { get; set; }
    public List<Course> Courses { get; set; }
}

This generates a table in database called CourseStudents table which contains 1 composite Primary key and 2 foreign Keys as expected.

THE QUESTION IS:

I want to create a simple Create view contains Student name and list of Courses (displayed as checkboxes), the selected checkboxes is stored in CourseStudents table

How to do that?

Abdallah Sabri
  • 431
  • 4
  • 20
  • 1
    You need to create view models to represent what you want to display/edit (and your `CourseVM` will contain a property `bool IsSelected` for binding to the checkbox). Refer [this answer](http://stackoverflow.com/questions/29542107/pass-list-of-checkboxes-into-view-and-pull-out-ienumerable/29554416#29554416) for an example –  May 11 '16 at 23:17

1 Answers1

2

on submit 1. Create new student object. 2. add selected courses to student object couse list

myStudent.Courses.add(selectedCourse);
  1. after adding all courses add student to dbContext and save changes to dbContext

    context.students.add(myStudent)
    context.SaveChanges();

if the student already exist just select it and add courses to selected student list and save changes to dbContext

Tawfiq abu Halawah
  • 1,214
  • 1
  • 12
  • 20
  • you cant add a check box for a list. – Tawfiq abu Halawah May 11 '16 at 20:00
  • if you want to do that you need to create a viewModel for your HTML view. in view model you can represent the list of courses as list of Booleans and you need to use a for loop `foreach(var courseVm in model.Coures){
  • ` http://stackoverflow.com/questions/14730746/getting-checkbox-value-in-asp-net-mvc-4 – Tawfiq abu Halawah May 12 '16 at 07:55