I would like to know if there is a way to popuplate a model from dropdownlist selection. For example:
My view is bound to the model Employee and the Employee class has a property 'Department' which is another class with its own properties:
My Employee View Model:
public class Employee
{
public string EmployeeName{get;set;}
public Department EmployeeDepartment{get;set;}
public List<Department> AvailableDepartments {get;set;}
}
Department Model:
public class Department
{
public string Code{get;set}
public string Name{get;set;}
public string Description{get;set;}
}
In my view where I enter the employee details I use a dropdown to let the user choose employee department.
@Html.DropDownListFor(
m => m.EmployeeDepartment,
new SelectList(@Model.AvailableDepartments , "Code", "Name")
)
When I submit the form, I get an instance of 'Employee Class' at the controller but obviously the EmployeeDepartment property will be null.
I am aware that if I add a string property 'EmployeeDepartmentCode' and map it to the dropdownlist, it will work. But is there any way I can populate the Department model property rather than using a string property? - because this view model is also used in a grid where it shows the employee department name.