Frage

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.

War es hilfreich?

Lösung

Well, if your EmployeeDepartment type looks like this:

public class EmployeeDepartment {
  public int ID { get; set; }
  // + other properties
}

Then you can just change your razor code to:

@Html.DropDownListFor(
  m => m.EmployeeDepartment.ID, 
  new SelectList(@Model.AvailableDepartments , "Code", "Name")
)

And then, when you receive the model back in again, the model will contain a non-null EmployeeDepartment with the ID set.

However, I think you're asking if you can then have the model binder automatically go and fetch the rest of the record from the database and fill in the rest of the data? If so, that's a more complex problem - but you can easily patch that up in the controller.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top