I'm trying to get a dropdown working on the create view for a particular model object. In this case, the model in question is Department, and within that object, there is another model object referenced called Division.
My Department model is a fairly basic POCO except for the property called Division which references another POCO (which, mind you, has simply an Id field and a Name field for the most part).
I already have a working dropdown for the create view (see code below)
<div class="form-group">
<label asp-for="Division" class="control-label"></label>
@Html.DropDownListFor(dept => dept.Division, new SelectList(ViewBag.Divisions, "Id", "Name"))
</div>
Yes, in the Create method that returns the view I'm populating the ViewBag.Divisions list and that's all working as planned.
However, in the Create method of my controller, while it's binding to the other (text) fields on the view I cannot figure out how to get it to populate the Division property for the Department object with the selection from the drop-down. My create method is below:
public async Task<IActionResult> Create([Bind("Id,Name,Description,IsActive,Division")] Department department)
{
if (ModelState.IsValid)
{
_context.Add(department);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(department);
}
Also, here are my model classes:
public class Division
{
[Key]
public int Id { get; set; }
[Required]
[Display(Name = "Division Name")]
public string Name { get; set; }
[Display(Name = "Active")]
public bool IsActive { get; set; }
}
public class Department
{
[Key]
public int Id { get; set; }
[Required]
[Display(Name = "Department Name")]
public string Name { get; set; }
public string Description { get; set; }
public Division Division { get; set; }
[Display(Name = "Active")]
public bool IsActive { get; set; }
}
The idea being that a particular department belongs to (and is associated with) a single division.
Thanks!
Divisionis actually a complex object, and you cannot bind a<select>to a complex object (in binds to a posts back a simple value (int,stringetc)