I am very new to MVC, so bear with me, but I cannot bind the value from SelectList to an instance of the selected object during postback in MVC 4.
Suppose I have to create Teacher as a member of the school. I have a ViewModel class defined as such:
public class RegisterTeacherModel { [Required] [Display(Name = "User name")] public string UserName { get; set; } [Required] [DataType(DataType.EmailAddress)] [Display(Name = "Email address")] public string Email { get; set; } [Required] [Display(Name = "School")] public School SelectedSchool { get; set; } [ScaffoldColumn(false)] public Guid UserId { get; set; } public SelectList PossibleSchools { get; private set; } public RegisterTeacherModel(IRepository<School> schoolRepo) { PossibleSchools = new SelectList(schoolRepo, "Id", "Name"); } }
And my view:
@using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>RegisterTeacherModel</legend> <div class="editor-label"> @Html.LabelFor(model => model.UserName) </div> <div class="editor-label"> @Html.LabelFor(model => model.Email) </div> <div class="editor-field"> @Html.EditorFor(model => model.Email) @Html.ValidationMessageFor(model => model.Email) </div> <div class="editor-label"> @Html.LabelFor(model => model.SelectedSchool) </div> <div class="editor-field"> @Html.DropDownListFor(model => model.SelectedSchool, Model.PossibleSchools) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> }
And finally, my controller method:
[HttpPost, ActionName("Create")] public ActionResult CreateTeacher(RegisterTeacherModel teacherModel) { if (ModelState.IsValid) { try { ... } } }
But when I get the RegisterTeacherModel object back to my Create method in the controller, SelectedSchool is always null. There must be something missing for me in the way the connecting device models the repeated creation of references to objects during postback. Can someone point me in the right direction?
source share