Izzy
Izzy

Reputation: 6866

Select selected value in drop down list

I have an enum which looks something like

public enum Department
{
    Admin,
    HR,
    Marketing,
    Sales
}

From this I am trying to create a drop down list in the controller and I do it like

public SelectList GetDepartmentDropDownList(string departmentName = null)
{
    var departments = Enum.GetValues(typeof(Department));
    SelectList ddl = new SelectList(departments);

    return ddl;
}

Which works fine. But as you can see I can pass in the opitional parameter. This optional parameter is passed in when the dropdown value is saved to the database and the user comes back to edit the section. What I am trying to achieve is whatever the user originally selected, when they come back on the edit screen that particular item is select i.e if they selected HR when they come back HR should be selected.

If I do new SelectList(departments, departmentName, departmentName); I get the following error:

DataBinding: Enums.Department' does not contain a property with the name 'HR'

Can someone suggest how to achieve this please.

In the view I am making using of Html.DropDownListFor() as

@Html.DropDownListFor(m => m.Department, Model.DepartmentDdl, "Please select a Department", new { @class = "form-control", @required = "required" })

The property in my model is

public IEnumerable<SelectListItem> DepartmentDdl { get; set; }

And in the controller create action I do

model.DepartmentDdl = GetDepartmentDropDownList();

And in the controller edit action I do

model.DepartmentDdl = GetDepartmentDropDownList(departmentName); //department name here is read from the db

Upvotes: 0

Views: 70

Answers (1)

user3559349
user3559349

Reputation:

Model binding works by binding to the value of your property. You need to set the value of property Department in the GET method before you pass the model to the view, for example

var model = new YourModel
{
    Department = Department.HR,
    DepartmentDdl = GetDepartmentDropDownList()
};
return View(model);

Note that there is no need for your parameter in the GetDepartmentDropDownList() method. Internally, the DropDownListFor() method builds a new IEnumerable<SelectListItem> and sets the Selected value of each SelectListItem based on the property your binding to (i.e. setting it in the SelectList constructor is ignored).

Upvotes: 1

Related Questions