如何从多选列表中获取所选项目并将它们绑定在多对多关系表中 [英] How to get selected items from multiselect list and bind them in many to many relationship table

查看:62
本文介绍了如何从多选列表中获取所选项目并将它们绑定在多对多关系表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有学生表和课程表他们之间的关系是由Student_Courses表做出的多对多关系。

i想要选择学生在注册新学生时将要学习的科目



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



这是模型中的课程类。

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/ [ ^ ]





这是createStudent查看





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;
       }

       //
       // 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/ [ ^ ]

推荐答案

这篇关于如何从多选列表中获取所选项目并将它们绑定在多对多关系表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆