来自其他模型的下拉列表 mvc5

Dropdown list mvc5 from other model

第一次使用 MVC 开发应用程序,运行 遇到了一个问题,即在学生创建视图的下拉列表中填充教师列表。

我有2个模型

public class Student
{

    [Required]
    [Display(Name = "ID")]
    public int ID { get; set; }
    [Required]
    [StringLength(100)]
    [DataType(DataType.Text)]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }
    [Required]
    [StringLength(100)]
    [DataType(DataType.Text)]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }
    [Required]
    [DataType(DataType.Date)]
    [Display(Name = "Date of Birth")]
    public DateTime? DateOfBirth { get; set; }
    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "Email Address")]
    public string EmailAddress { get; set; }
    [Required]
    [DataType(DataType.PhoneNumber)]
    [Display(Name = "Contact Number")]
    public string ContactNumber { get; set; }
    [Required]
    [StringLength(100)]
    [DataType(DataType.Text)]
    [Display(Name = "Parent/Guardian Name")]
    public string ParentGuardianName { get; set; }

    public Teacher Teacher { get; set; }


    public MembershipOption MembershipOption { get; set; }

    public ICollection<Progress> Progress { get; set; }
    public ICollection<Report> Report { get; set; }
    [DataType(DataType.Date)]
    [Display(Name = "Signed Up Date")]
    public DateTime? SignedUpDate { get; set; }
    [Display(Name = "Active")]
    public bool Active { get; set; }



}

 public class Teacher
{
    [Required]
    [Display(Name = "ID")]
    public int ID { get; set; }
    [Required]
    [StringLength(100)]
    [DataType(DataType.Text)]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }
    [StringLength(100)]
    [DataType(DataType.Text)]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }
    [Display(Name = "Active")]
    public bool Active { get; set; }
    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }

}

}

我有如下所示的学生模型的创建视图

    <div class="form-group">
    @Html.LabelFor(model => model.ParentGuardianName, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(m => m.Teacher, // 1. Store selected value in Model.State;
                                         // when page is rendered after postback,
                                         // take selected value from Model.State.

                                       // 2. Take list of values from Model.States
                                       Model.Teacher,

                                       // 3. Text for the first 'default' option
                                       "- Please select a Teacher -",

                                       //4. A class name to assign to <select> tag
                                       new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Teacher, "", new { @class = "text-danger" })
    </div>
</div>

Teachers 的下拉列表因 Teacher 为空而引发异常。

我如何将教师下拉列表添加到这个学生创建的 cshtml?

我假设我需要在调用学生模型时获取教师,但不确定它需要放在学生控制器中的什么位置?

第二个参数应该是 SelectListItem 的列表,以便辅助方法可以使用该列表生成 SELECT 选项。但是您正在尝试传递 Teacher 导航 属性 而不是那个!

您应该为您的视图创建一个视图模型,它具有接受表单输入值的属性。由于您想向视图添加下拉列表,因此向视图模型添加 2 个属性。一个用于选定的值,一个用于我们需要用来呈现下拉列表的项目列表

public class CreateStudent
{
    [Required]
    [StringLength(100)]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Required]
    [StringLength(100)]
    [Display(Name = "Last Name")]
    public string LastName { get; set; } 

    // to do : Add other properties AS NEEDED BY THE VIEW
    // Do not just copy all the properties from Entity class

    public List<SelectListItem> Teachers { set; get; }

    [Required]
    [DisplayName("Select Teacher")]
    public int SelectedTeacherId { set; get; }
}

现在在您的 GET 操作中,您需要创建此视图模型的对象,填充 Teachers 集合 属性 并将该对象发送到视图

public ActionResult Create()
{
    var vm = new CreateStudent();
    vm.Teachers = GetTeachers();
    return View(vm);
}

private List<SelectListItem> GetTeachers()
{
    return db.Teachers.Select(a => new SelectListItem
    {
        Value = a.Id.ToString(),
        Text = a.Name
    }).ToList();
}

现在在您的视图中,我们的视图模型是强类型的,我们可以使用 DropDownListFor 辅助方法来呈现 SELECT 元素

@model CreateStudent
@using(Html.BeginForm())
{
    @Html.LabelFor(a=>a.FirstName)
    @Html.TextBoxFor(a=>a.FirstName)

    @Html.LabelFor(a=>a.LastName)
    @Html.TextBoxFor(a=>a.LastName)

    @Html.LabelFor(a=>a.SelectedTeacherId)
    @Html.DropDownListFor(a=>a.SelectedTeacherId , Model.Teachers, "select one")

    <input type="submit" />
}

现在在你的 HttpPost 操作中,使用与你的操作方法参数相同的视图模型,并从它的属性中读取值并使用它来创建你的实体的新对象 class 并保存它

[HttpPost]
public ActionResult Create(CreateStudent model)
{
  if(ModelState.IsValid)
  { 
     var s = new Student { FirstName=model.FirstName };
     s.LastName = model.LastName;
     // to do : Map other property values as well from view model
     db.Students.Add(s);
     db.SaveChanges();
     return RedirectToAction("Index");
  }
  //Make sure to RELOAD the Teachers list for dropdown
  model.Teachers = GetTeachers();
  return View(model);
}