我需要用数据库中的数据填充两个列表框。 但是我需要在一个 View 中显示两个列表框,所以我创建了一个 ListBoxModel 类。
public class ListboxModel
{
public ListBox LB1 { get; set; }
public ListBox LB2 { get; set; }
}
在我的 Controller 中:
public ActionResult IndexStudents(Docent docent, int lessonid, int classid)
{
var MyListBox = new ListboxModel
{
LB1 = new ListBox(docent.ReturnStudentsNormal(lessonid, classid),
LB2 = new ListBox(docent.ReturnStudentsNoClass(lessonid, classid)
};
return View(MyListBox);
}
但是这段代码不起作用,我怎样才能将数据绑定(bind)到列表框呢? 所以我想使用 2 个模型,每个列表框一个……一个是普通学生,一个是未订阅类(class)的学生。 我怎么能那样做? 在我看来我必须编写什么代码? 像这样的东西:
<div class="editor-field">
<%: Html.ListBox("IndexStudentsNormal", Model.LB1) %>
<div class="editor-field">
<%: Html.ListBox("IndexStudentsNoClass", Model.LB2) %>
列表框必须是具有多个列的列表框,以便它可以包含学生的姓名、先生姓名、类(class)、老师。
Student 是一个对象,我想在该列表框中显示 student.Name、student.Sirname、student.Class 等。
那么我可以在 ListBox 中使用对象,还是必须将所有内容都转换为字符串?
我该怎么做?
提前致谢!
最佳答案
模型不应包含列表框,而应仅包含学生列表。诀窍是让模型尽可能简单,它实际上应该只是一堆属性 getter 和 setter。 View 负责将模型的属性绑定(bind)到 HTML 元素。
型号:
public class StudentModel
{
public IList<string> NormalStudents {get;set;}
public IList<string> NoClassStudents {get;set;}
}
Controller :
public ActionResult IndexStudents(Docent docent, int lessonid, int classid)
{
var studentModel = new ListboxModel
{
NormalStudents = docent.ReturnStudentsNormal(lessonid, classid),
NoClassStudents = docent.ReturnStudentsNoClass(lessonid, classid)
};
return View(studentModel);
}
查看:
<div class="editor-field">
<%: Html.ListBox("IndexStudentsNormal", Model.NormalStudents) %>
</div>
<div class="editor-field">
<%: Html.ListBox("IndexStudentsNoClass", Model.NoClassStudents) %>
</div>
关于c# - ASP.NET MVC : populate (bind data) in listbox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7000437/