如何在VS2010 MVC3中使用网格添加和编辑数据?

时间:2013-05-25 06:58:02

标签: c# asp.net-mvc visual-studio-2010 asp.net-mvc-3 grid

我正在使用Microsoft VS 2010 C#,MVC3。 我有Calsserooms和学生有很多关系,所以我添加了一个名为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);             
        }
    }

1 个答案:

答案 0 :(得分:0)

嗯,要求对标记进行最少更改的选项是将multiple属性添加到select。然后,更改操作方法以接受params int[] ids,迭代它们,您应该是好的去。在最坏的情况下,您可能需要将参数更改为string并在Split()上执行,,但我不记得模型绑定器如何支持多选。< / p>

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

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