0

我正在使用 Microsoft VS 2010 C#、MVC3。我有具有多对多关系的 Calsserooms 和 Student,因此我添加了一个名为 Classroom_Students 的中间表。将学生添加到教室时,我在视图中使用了一个组合框,其中填充了所有学生的姓名,我在每次提交时一一选择

@using (Html.BeginForm("AddStudentToClassroom", "Calssrooms", FormMethod.Post))
{
@Html.LabelFor(c=>c.Students, "Choose a Student")

            <select name = "StudentID">
                @foreach (var it in Model.Students)
                {
                    <option value="@it.ID">@it.StudentName </option>
                }    
            </select>

            <input type="submit" value= "Add" />
}

我的问题是:如何使用 gride 而不是这个组合来选择许多学生,全选或取消全选以添加?我会很感激任何帮助。

这是我的控制器中的代码。对于页面第一次调用,我填写组合框如下:

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult AddStudentToClassroom(int id)   //id of calssroom
{
    using (ExaminationEntities en = new ExaminationEntities())
    {
        ClassroomDetails ClsromView = new ClassroomDetails ();     // these are for 
        ClsromView.Classroom = en.Classroom.Single(c => c.ID == id);// loading calssroom information and to
            ClsromView.Students = en.Students.ToList();         // fill students list for the combobox
            return View(ClsromView);
        }
    }

在提交表单、视图、点击添加按钮时,会调用如下重载的添加函数来保存数据:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddStudentToClassroom(AddStudToCals ClasStud)   //ClasStud is the submited data from the view
{
     using (ExaminationEntities en = new ExaminationEntities())
     {
         ClassroomDetails ClsromView = new ClassroomDetails();          // these are for 
         ClsromView.Calssroom = en.Calssroom.Single(c => c.ID == ClasStud.ClassroomID); // loading calssroom information and to
         ClsromView.Students = en.Student.ToList();                     // fill students list for the combobox

          using (ExaminationEntities exn = new ExaminationEntities())
          {
              Calssroom_Student To_DB_ClasStud = new Calssroom_Student ();      //To_DB_ClasStud object to get the submited values and to save it in the DB
              To_DB_ClasStud.CalssroomID = ClasStud.CalssroomID;
              To_DB_ClasStud.StudentID = ClasStud.StdentID;
              en.AddToClassroom_Student(To_DB_ClasStud);
              en.SaveChanges();
           }
                return View(ClsromView);             
        }
    }
4

1 回答 1

0

好吧,需要对标记进行最少更改的选项是将multiple属性添加到您的select. 然后,将 action 方法更改为接受 a params int[] ids,遍历它们,你应该可以开始使用了。在最坏的情况下,您可能必须将参数更改为 astring并执行 a Split()on ,,但我不记得模型绑定器是如何支持多选的。

如果这似乎不符合您的需要,ASP.NET 网站上有一篇文章解释了使用 aMultiSelectList绑定到ListBox帮助程序,这里:

http://www.asp.net/mvc/tutorials/javascript/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc

于 2013-05-25T07:31:37.980 回答