使用第一种方法我在列表框中设置默认主题,而使用第二种方法我只检索这些被选中的人。
public void SubjectsList()
{
ViewBag.Subjects =
new SelectList(new[] { "Math", "Physic", "English" }
.Select(x => new { value = x, text = x }),
"Value", "Text");
}
public void SubjectsFromDb(int id)
{
var students = _db.Subjects.AsEnumerable().Where(x => x.StudentId == id).Select(q => new SelectListItem
{
Value = q.Name,
Text = q.Name,
}).ToList();
ViewBag.Subjects = students;
}
我如何才能在Listbox中做到这一切,但所选的只是在db?
中的所有主题这是我的列表框
<div class="form-group">
@Html.LabelFor(model => model.Subject, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.ListBoxFor(model => model.Subject,
new MultiSelectList((IEnumerable<SelectListItem>)ViewBag.Subjects, "Value", "Text"),
new { style = "display:block;" })
@Html.ValidationMessageFor(model => model.Subject)
</div>
</div>
答案 0 :(得分:0)
您的模型属性Subject
必须为public IEnumerable<string> Subject { get; set; }
,但我建议将其重命名为Subjects
- 复数)并重命名ViewBag
属性
在GET方法中,将现有主题分配给模型
var model = yourModel()
{
Subjects = _db.Subjects.Where(x => x.StudentId == id).Select(q => q.Name);
};
ViewBag.SubjectList = new SelectList(new[] { "Math", "Physic", "English" });
return View(model);
然后在视图中
@Html.ListBoxFor(m => m.Subjects, (SelectList)ViewBag.SubjectList)
附注:
SelectList
的对象 - 您可以删除.Select(x => new { value = x, text = x }), "Value", "Text")
SelectList
,因此无需额外费用
创建另一个重复SelectList
的开销
ListBoxFor()
方法