I'm having a real hard time trying to set up a drop-down list to a related model/table in my create view. My Guest model has a reference to the PersonPrefix model in the following way:
Guest model:
public virtual PersonPrefix Prefix { get; set; }
PersonPrefix model:
public class PersonPrefix
{
[Key]
public int PersonPrefixID { get; set; }
[StringLength(6)]
public string Abbreviation { get; set; }
[StringLength(255)]
public string Name { get; set; }
public virtual ICollection<Guest> Guests { get; set; }
}
I have done the following to be able to get the data from the database and show it in a dropdown:
Controller:
public ActionResult Create()
{
ViewBag.PersonPrefixes = new SelectList(db.PersonPrefixes, "PersonPrefixID", "Abbreviation");
return View();
}
and I've added the prefix object to the post
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "GuestID,FirstName,MiddleName,Surname,BirthDate,SelectedPrefix")] Guest guest)
{
if (ModelState.IsValid)
{
db.Guests.Add(guest);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(guest);
}
This is the relevant code in the view so far but it is not passing the value to the controller:
<div class="form-group">
@Html.LabelFor(model => model.Prefix, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10" >
@*@Html.DropDownListFor(m => m.Prefix, new SelectList(ViewBag.PersonPrefixes, "Value", "Text", 1))*@
@Html.DropDownListFor(m => m.Prefix,
new SelectList(ViewBag.PersonPrefixes, "Value", "Text", 1))
</div>
</div>
Thanks for your help!!