【问题标题】:ASP MVC Access Dropdownlist from Database来自数据库的 ASP MVC 访问下拉列表
【发布时间】:2016-09-30 10:56:13
【问题描述】:

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

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


}

【问题讨论】:

    标签: asp.net-mvc model-view-controller drop-down-menu ado.net


    【解决方案1】:

    您需要创建操作方法,它将填充您的下拉列表。您需要设置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)
    

    在POST方法中

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-17
      • 2016-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多