ASP MVC 从数据库访问下拉列表

ASP MVC Access Dropdownlist from Database

我正在创建一个 SchoolManagement 应用程序,我必须在其中创建一个 StudentRegistration 表单。在表单页面上,我必须显示也将来自数据库的 Dropdownlist。我是 asp mvc 的新手,在 asp.net 中很容易,但在 MVC 中我不知道该怎么做。我正在使用 Ado.net 和 Razor 视图引擎。请有人指导需要哪些步骤。 这是我的模型 class

 public class StudentModel
{
    [Required(ErrorMessage="Student ID is required", AllowEmptyStrings=false)]
    public int StudentID { get; set; }
    [Required(ErrorMessage = "Student Roll No is required", AllowEmptyStrings = false)]
    public int RollNo { get; set; }
    [Required(ErrorMessage = "Student Name is required", AllowEmptyStrings = false)]
    public string StudentName { get; set; }
    [Required(ErrorMessage = "Student Address is required", AllowEmptyStrings = false)]
    public string Address { get; set; }
    [Required(ErrorMessage = "Student Cell is required", AllowEmptyStrings = false)]
    public string Cell { get; set; }


}

您需要创建操作方法,它将填充您的下拉列表。您需要设置 SelectedListItem 的列表。 所以,解释一下你使用 entity framework。

你的方法将是这样的。

public ActionResult Register()
{
    var model = new RegistrationViewModel()
    {
       StudentsList = this.context.Students.Select(s => new SelectListItem
         {
             Text = s.Name,
            Value = s.Id.ToString()
         },
    // some other property to the model
    }

    return View(model);
}

在视图中:

//SelectedStudent - string property in your model, where will be stored Value from list

@Html.DropDownListFor(model => model.SelectedStudent, Model.StudentsList)

并且在POST方法中

[HttpPost]
public ActionResult Register(RegistrationViewModel model) 
{
    var studentId = int.Parse(model.SelectedStudent);
}