0

I wanted to add the value of checkbox ids to many to many relation table between two tables Course-Student

i have 3 tables Course{ CourseID,CourseName }, Studdent{StudentID,StudentName} and CourseStudet{CourseID, StudentID} Course table already have course{1.DataScience,2.English,3.Physics} while Inserting Student i have shown course checkboxes with these options fetching list of these courses from database to show in view to user when he is about to register now i am confused how to insert into database?

public class CourseModel {

        public List<Course> mycourse{ get; set; }

        public string StudentName {get; set;}


    }

EF generated Class

 public partial class Course
    {
        public Course()
        {
            this.Student= new HashSet<Student>();
        }

        public int CourseID { get; set; }
        public string CourseName { get; set; }

        i have inserted this field to check for checked value
        public bool Ischecked { get; set; }

        public virtual ICollection<Student> Student { get; set; }
    }


 public partial class Student
    {

        public Student()
        {
            this.Course= new HashSet<Course>();
        }

        public int StudentID { get; set; }
        public string StudentName { get; set; }


        public virtual ICollection<Course> Course{ get; set; }
    }

 public ActionResult Index()
        {
            CourseModel coursemodel = new CourseModel();
            using (Entities db = new Entities())
            {
                coursemodel.mycourse = db.Course.ToList<Course>();

                 return View(coursemodel);

            }


        }
        [HttpPost]
        public ActionResult Index(CourseModel course)
        {       
            return View(course);
        }

View

@using (Html.BeginForm("index", "Course", FormMethod.Post))

         <input type="Text" name="StudentName" placeholder="Name" />

{
    <table>
        @for (int i = 0 ; i < Model.mycourse.Count; i++)
        {
            if (i % 3 == 0) {
                @:<tr></tr>
            }
        <div>

            @Html.CheckBoxFor(x => x.mycourse[i].Ischecked)
            <label>@Model.mycourse[i].CourseName</label>
            @Html.HiddenFor(x => x.mycourse[i].CourseID)
            @Html.HiddenFor(x => x.mycourse[i].CourseName)
        </div>



        }

    </table>
   <input type="submit" value="Submit" />
}

i am getting checkbox id,name and which course is checked now how can i add student with including these values to relationship table CourseStudent ?

  • In CourseStudent you can have a single student with many courses. it would be helpful if you show where you are inserting the student so that we don't just write random code – Bosco Jul 24 '19 at 04:27
  • You can AddRange for list I. Your CourseStudent table or use a for loop to insert each. Just show the code inserting for students and we will be able to help properly – Bosco Jul 24 '19 at 11:41
  • I just added a property of studentName in CourseModel which i will get in parameter in Controller now how will i add the student name to Student Table? and List values of Checkbox which are ischecked == true how can i add their values to CourseStudent table ? against student which we just Added ? – Sohail Shah Jul 24 '19 at 11:41
  • Student just have a single property which is its name why would i add it differently ? cant i just add both at the same Controller ? – Sohail Shah Jul 24 '19 at 11:45
  • Did you check the new answer? – Shervin Ivari Jul 24 '19 at 17:47

1 Answers1

0

You have problems with your database design. Remove ischecked field.Remember while you are designing entities, you shouldn't put fields that are for view. It is like that I make Reports table from my each query.

correct your models

  public partial class Course
{
    public Course()
    {
        this.Student = new HashSet<Student>();
    }

    public int CourseID { get; set; }
    public string CourseName { get; set; }

    public virtual ICollection<Student> Student { get; set; }
}


public partial class Student
{

    public Student()
    {
        this.Course = new HashSet<Course>();
    }

    public int StudentID { get; set; }
    public string StudentName { get; set; }

    public virtual ICollection<Course> Course { get; set; }
}

Add viewmodels(You can use view models for showing custom data for your view) You can read more

ViewModel

public class CourseViewModel
{
    public Course course { get; set; }
    public bool CheckBox { get; set; }
}

public class StudentCourseViewModel
{
    public List<CourseViewModel> coursesVM { get; set; }
    public Student student { get; set; }
}

Controller

  public ActionResult index()
  {
      Entities db = new Entities();
      List<CourseViewModel> courselist = new List<CourseViewModel>();
      foreach (var item in db.Course.ToList())
        {
            courselist.Add(new CourseViewModel { course = item});
        }
      StudentCourceViewModel model = new StudentCourseViewModel(
      {
          student = new student(),
          coursesVM = courselist   }
      };
      return View(model);
  }
  [HttpPost]
  public ActionResult Save(StudentCourseViewModel model)
  {
      Entities db = new Entities();
      Student stdindb = db.Students.FirstorDefault(c => c.StudentName == model.student.StudentName); 
      if(stdindb == null)
      {
       stdindb = new student(){//your properties};
       db.students.add(stdindb);
      }
      foreach (var item in model.coursesVM)
      {
        if (item.Ischecked)
          {
            stdindb.Course.Add(db.course.single(c=>c.CourseId == item.course.CourseId ));
          }
        }
        db.SaveChanges();
        return View();
  }

View

@model SchoolCMS.Models.StudentCourseViewModel
@{
    ViewBag.Title = "Select Course";
}

@using (Html.BeginForm("Save", "home", FormMethod.Post))
{
@Html.TextBoxFor(c=>c.student.StudentName)
<table>
    @for (int i = 0; i < Model.coursesVM.Count; i++)
    {
        <tr>
            <td>
            @Html.CheckBoxFor(c => c.coursesVM[i].Ischecked)
            @Html.HiddenFor(c => c.coursesVM[i].course.CourseID)
        </td>
        <td>@Html.DisplayFor(c => c.coursesVM[i].course.CourseName)</td>
    </tr>
    }
    </table>
    <input type="submit" value="Submit" />
}
Shervin Ivari
  • 1,759
  • 5
  • 20
  • 28
  • coursesVM = new CourseViewModel {course = db.Course.ToList() error on this line "Cannot implicitly convert type system.collections.generic.list to Course" – Sohail Shah Jul 24 '19 at 20:10
  • @SohailShah check out new answer – Shervin Ivari Jul 24 '19 at 20:20
  • Thank you for your time man but still this line "courselist.Add(new CourseViewModel { course = item});" giving the same error on item – Sohail Shah Jul 24 '19 at 20:36
  • @SohailShah Your welcome, both of them have the same type. whats error?I don't have the source you can guess what's wrong. check the types – Shervin Ivari Jul 24 '19 at 21:01
  • well that was only for the View which i have already shown up the list by other method my original question still remain i am getting checkbox id,name and which course is checked now how can i add student with including these values to relationship table CourseStudent ? if you can help me after the post Action ? – Sohail Shah Jul 24 '19 at 21:08
  • yeah i have already did that just added a ischecked column on database course table so that there wont be an issue. :) now the real question still remain :P – Sohail Shah Jul 24 '19 at 21:18
  • @SohailShah How do you want to save the wrong data?ischecked won't work for your bridge table,that's why I say to correct your entity – Shervin Ivari Jul 24 '19 at 21:25
  • @SohailShah if you want to follow the way you mention in your question.check save in controller,just the condtion will change.Do you get model successfuly in post action? – Shervin Ivari Jul 24 '19 at 21:29
  • yeah i get model successfully in post action ill check the save one and will let u know :) – Sohail Shah Jul 24 '19 at 21:37
  • this link will help you,https://stackoverflow.com/questions/6113570/entity-framework-4-inserting-with-foreign-key-value-not-id – Shervin Ivari Jul 24 '19 at 21:46
  • Thank you so much man your Post one worked :) Thanks once again :) – Sohail Shah Jul 24 '19 at 22:43
  • @SohailShah No problem,Happy to help – Shervin Ivari Jul 25 '19 at 08:50
  • Just one more thing the solution you provide first find the user in database if found then the course then add both on relationship table right ? what if the student isnt found on the database ? how would we add student first then then check its id then add the relation? simply can we add student and course at the time of registration for student ? – Sohail Shah Jul 25 '19 at 11:11
  • @SohailShah Sure. Just change Single with FirstorDefault this will return null if the model does not find in database then you can save it first then add the course.Check my answer – Shervin Ivari Jul 25 '19 at 13:54