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?

1
  • 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 for an example Commented May 11, 2016 at 23:17

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

How you could use check box, this line of code is not valid @Html.CheckBoxFor(model => model.Courses, new { value=course.ID })@course.Title
foreach(var courseVm in model.Coures){ <li><input type="checkbox" name="[email protected]" value="@course.Title" checked="@courseVm.isSelected" /> </li>
you cant add a check box for a list.
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){ <li><input type="checkbox" name="[email protected]" value="@course.Title" /> </li> stackoverflow.com/questions/14730746/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.