【问题标题】:Passing a ViewBag to Listboxfor将 ViewBag 传递给 Listboxfor
【发布时间】:2023-03-25 15:18:01
【问题描述】:

在我看来,我想显示一个 CheckBoxList,它将显示所有学生的姓名。检查每个学生最终将标记他们的出勤率。我想要做的是传递一个 ViewBag (据说)包含学生的 SelectList。

这是我在 Controller 中尝试做的事情。

public ActionResult Create(int? id)
    {
        List<SelectListItem> selectListItems = new List<SelectListItem>();

        var @class = db.Classes.Find(id);
        var students = @class.Students.ToList();
        foreach (Student student in students)
        {
            SelectListItem item = new SelectListItem()
            {
                Text = student.St_name,
                Value = student.St_id.ToString(),
                Selected = student.IsSelected
            };
            selectListItems.Add(item);
        }
        ViewBag.students = selectListItems;
        var timetables = @class.Timetables.ToList();
        ViewBag.Sat_ti_fk_id = new SelectList(timetables, "Ti_id", "Ti_day");
        return View();
    }

这就是我在视图中所做的事情

<div class="form-group">
        @Html.LabelFor(model => model.Sat_st_fk_id, "Sat_st_fk_id", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.ListBoxFor(ViewBag.students, htmlAttributes: new { @class = "control-label col-md-2" })
            @Html.ValidationMessageFor(model => model.Sat_st_fk_id, "", new { @class = "text-danger" })
        </div>
    </div>

但是 ListBoxFor 方法显示错误,说它需要 2 个参数。 任何形式的帮助都是值得赞赏的。 谢谢。

【问题讨论】:

  • 你能把这个htmlAttributes:删掉试试

标签: c# asp.net razor


【解决方案1】:

@Html.ListBoxFor 接受三个参数

  1. 存储值的属性
  2. 显示为 SelectList 的数据列表
  3. HTML 属性(可选

你应该把@Html.ListBoxFor改成这个

 @Html.ListBoxFor(model => model.Sat_st_fk_id, ViewBag.students as SelectList, new { @class = "control-label col-md-2" })

【讨论】:

  • 谢谢,它成功了。但是我的列表框现在甚至是空的。我会看看是什么问题。
  • @razaabbas 你想显示students 列表还是Sat_ti_fk_id
  • 我需要传递学生列表,它存储在名为 Sat_ti_fk_id 的 viewbag 中。我找到了问题所在,多亏了你,现在一切都很好。
猜你喜欢
  • 1970-01-01
  • 2015-01-07
  • 2012-01-11
  • 1970-01-01
  • 1970-01-01
  • 2013-02-23
  • 1970-01-01
  • 1970-01-01
  • 2016-10-08
相关资源
最近更新 更多