Click here to Skip to main content
15,891,657 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have student table and Courses table the relationship between them is many to many relationship made by Student_Courses table.
i want to select subjects which the student will study when register a new student

http://postimg.org/image/enzvw2svz/[^]

here is the courses class in the model.
C#
public partial class TblCours
    {
        public TblCours()
        {
            this.TblStudents = new HashSet<TblStudent>();
        }

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

        public virtual ICollection<TblStudent> TblStudents { get; set; }
    }


and this is the student class in the model
C#
public partial class TblStudent
    {
        public TblStudent()
        {
            this.TblCourses = new HashSet<TblCours>();
        }

        public int StudentId { get; set; }
        public string StudentName { get; set; }
        public Nullable<short> StudentAge { get; set; }

        public virtual ICollection<TblCours> TblCourses { get; set; }
    }


http://postimg.org/image/f217voczj/[^]


this is the createStudent View

Razor
@{
    ViewBag.Title = "Create";
    SelectList items = ViewBag.subjectsList;
}
@model School.Models.TblStudent


<h2>Create</h2>
@using (Html.BeginForm())
{
    @Html.TextBoxFor(model => model.StudentId, new {  @class = "form-control" })
    @Html.TextBoxFor(model => model.StudentName, new {  @class = "form-control" })
    
     @Html.ListBoxFor(model => model.TblCourses, items as MultiSelectList);
    
    <input type="submit" class="btn btn-danger btn-lg center-block" onclick="validedStyle()" value="Add student">
     
}

and this is the controller actions

C#
public IEnumerable<TblCours> GetCourses()
       {
           List<TblCours> cntTable = model.TblCourses.ToList();
           return cntTable;
       }

       //
       // POST: /Student/Create

       [HttpPost]
       public ActionResult Create( TblStudent std)
       {
           try
           {
               model.TblStudents.Add(std);
               model.SaveChanges();
               ViewBag.subjectsList = new SelectList(GetCourses(), "CourseId", "CourseName");
               ViewBag.selection = GetCourses();
               return View();
           }
           catch
           {
               return View();
           }
       }


http://postimg.org/image/81d82wb7j/[^]
Posted
Updated 23-Jul-14 6:04am
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900