First time using MVC to develop an app and have run into an issues populating a dropdown in the student create view with a list of teachers.
I have 2 models
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; }
}
}
I have the create view of the student model that looks like this
<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>
The dropdownlist for Teachers throws an exception due to Teacher being null.
How do i go about adding the teachers drop down list to this student create cshtml?
Im assuming i need to get the teachers when the student model is called, but not sure where it needs to be put in the studentscontroller?