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.
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
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
@{
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
public IEnumerable<TblCours> GetCourses()
{
List<TblCours> cntTable = model.TblCourses.ToList();
return cntTable;
}
[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/[
^]