从其他模型下拉列表mvc5

时间:2018-05-22 02:14:06

标签: asp.net asp.net-mvc-5 dropdownlistfor

首次使用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>

由于教师为空,教师的下拉列表会抛出异常。

如何将教师下拉列表添加到此学生创建cshtml?

我假设我需要在调用学生模型时找到老师,但不确定它需要放在学生控制器的哪个位置?

1 个答案:

答案 0 :(得分:1)

第二个参数应该是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操作中,使用与您的操作方法参数相同的视图模型,并从其属性中读取值并使用它来创建实体类的新对象并保存它

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