c# - ASP.NET MVC : populate (bind data) in listbox

标签 c# asp.net-mvc model listbox

我需要用数据库中的数据填充两个列表框。 但是我需要在一个 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/

相关文章:

c# - 使用 EF 中的通用方法检查数据库中是否存在记录

c# - 合并基类和派生 C# 类的工具

ios - 更改 CoreData 模型 : retro compatibility

ruby-on-rails - 如何在 Ruby 类/模块命名空间中转换模型?

c# - 如何在 libtorrent 中设置客户端名称

c# - 从 xslt 中,您可以输出整个 XML 吗?

asp.net - 通过 SendGrid 向 Outlook 发送邮件总是失败

c# - 将父模型的一个元素传递给局部 View

asp.net-mvc - asp.net mvc 区域默认页面

java - 黑客可以更改模型属性吗? Spring , java