ASP.NET mvc : populate (bind data) in listbox

后端 未结 2 1283
慢半拍i
慢半拍i 2020-12-21 09:16

I need to populate two listboxes with data from a database. But I need to display two listboxes in one view, so I created a ListBoxModel class.

public class          


        
2条回答
  •  旧巷少年郎
    2020-12-21 09:52

    Based on Jason's answer, the first line in your view should include:

    <%@ Inherits="System.Web.Mvc.ViewPage" %>
    

    This tells your view that "Model" is of type StudentModel. If there's other bits in this first line (Title, Language, MasterPageFile, etc), they're fine to stay there.


    -- edit: add longish comments --

    The thing to remember is that a SelectListItem has three required parts: Value, Text, and Selected. Value is the key, so something like StudentId or DocentId. Text is displayed in the list, so something like StudentName or DocentName. Selected indicates whether this item is selected in the list, typically false.

    Right now it looks like you have methods that only return a list of the student names (Docent.ReturnStudentsNormal() and Docent.ReturnStudentsNoClass()). I would have these methods return a list of key-value pairs, key being StudentId and value being StudentName.

    Then you can change your model class to be

    public class StudentModel
    {
      List NormalStudents;
      List StudentsNoClass;
    }
    

    and in your controller

    public ActionResult IndexStudents(Docent docent, int lessonId, int classId)
    {
      var studentModel = new StudentModel();
    
      var normalStudents = docent.ReturnStudentsNormal(lessonId, classId);
      foreach (var student in normalStudents)
      {
        studentModel.NormalStudents.Add(new SelectListItem() {Value = student.Key, Text = student.Value});
      }
    
      var studentsNoClass = docent.ReturnStudentsNormal(lessonId, classId);
      foreach (var student in studentsNoClass)
      {
        studentModel.StudentsNoClass.Add(new SelectListItem() {Value = student.Key, Text = student.Value});
      }
    
      return View(studentModel);
    }
    

    Now you'll be able to use these properties on your model directly for Html.ListBox().

提交回复
热议问题