在Asp.net mvc4中创建一个CheckBox列表 - 显示来自Database的项目

时间:2013-06-17 11:38:54

标签: database asp.net-mvc-4 checkbox

嘿这是我的模型,我联合了3张桌子。

    public Student Student { get; set; }
    public Simester Semester { get; set; }
    public Lesson Lesson { get; set; }

这是我的控制器:

 [HttpGet]
        public ActionResult UnitSelection()
        {
            var students = context.Students;
            ViewBag.Students = new SelectList(students, "Id", "FullName");

            var semesters = context.Simesters;
            ViewBag.Semesters = new SelectList(semesters, "Id", "Title");

            var lessons = context.Lessons;
            ViewBag.Lessons = new SelectList(lessons, "Id", "Title");
            return View();
        }

        [HttpPost]
        public ActionResult UnitSelection(UnitSelectionViewModel model)
        {
            StudnetLesson snl = new StudnetLesson();
            snl.LessonId = model.Lesson.Id;
            snl.StudentId = model.Student.Id;
            snl.SimesterId = model.Semester.Id;
            context.StudnetLessons.Add(snl);
            context.SaveChanges();


            return RedirectToAction("Success");

        }

我想在foreach循环中的视图中显示一个复选框列表。 我想在复选框列表中显示课程(其字符串)

public Lesson Lesson { get; set; }

我测试了很多代码并且没有任何提示?

@using (Html.BeginForm("UnitSelection", "Home", FormMethod.Post))
        {
            <text>Student Name: </text>
            @Html.DropDownListFor(x => x.Student.Id, (SelectList)ViewBag.Students, "Choose a student")
            <br />
            <text>Semester: </text>
            @Html.DropDownListFor(x => x.Semester.Id, (SelectList)ViewBag.Semesters, "Choose your semester")
            <br />
            <text>Lesson: </text>
            foreach (var lessons in (SelectList) ViewBag.Lessons)
            {
            }

        }

1 个答案:

答案 0 :(得分:0)

将checkboxes属性添加到UnitSelectionViewModel

public List<string> lessonsList {get;set;}

然后在视图中绑定它

 foreach (var lessons in (SelectList) ViewBag.Lessons)
 {
    <input type="checkbox" name="lessonsList" value ="@lessons.Id" />
 }

然后在行动

UnitSelectionViewModel.lessonsList // here must be id of selectd lessons

回答评论。 我的脚本中的Id仅仅是例如。使用此字段的名称。

表示复选框。例如,查看here