1

我正在創建一個SchoolManagement應用程序,其中我必須創建一個StudentRegistration表單。在表單頁上,我必須顯示Dropdownlist,這也將來自數據庫。我是新來的asp MVC,它是如此容易在asp.net,但在MVC我不知道如何做到這一點。我正在使用Ado.net和Razor視圖引擎。請有人指導需要哪些步驟。 這是我的模型類來自數據庫的ASP MVC訪問下拉列表

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; } 


} 

回答

0

您需要創建操作方法,這將填補你的下拉列表。您需要設置SelectedListItem的列表。 所以,解釋你使用實體框架。

你的方法將是這樣的。

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) 

,並在後期的方法

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