@ Html.DropDownListFor with ViewBag SelectedListItem the selected item is not showing

My code is as follows:

Controller:

foreach (Employee engineer in engineers)
{                       
       if (!model.Customer.PrimaryEngineerId.Equals(engineer.EmployeeId)) 
       {
            engineersListPrimary.Add(new SelectListItem { Text = engineer.FirstName + ' ' + engineer.LastName, Value = engineer.EmployeeId, Selected = false});
       }
       else
       {
            engineersListPrimary.Add(new SelectListItem { Text = engineer.FirstName + ' ' + engineer.LastName, Value = engineer.EmployeeId, Selected = true });
       }                 
}
ViewBag.engineersListPrimary = engineersListPrimary;
return View(model);

      

View:

@Html.DropDownListFor(m => m.Customer.PrimaryEngineer, (IEnumerable<SelectListItem>)ViewBag.engineersListPrimary, new { style = "width:100%;"})

      

After a lot of searching and trying to put it, I was unable to print the selected value.

Problem:

The selected value does not appear in the DropDownListFor used in the view.

After debugging, I checked if the engineerListPrimary was filled in correctly (true = true line selected correctly), so the problem should remain in the view.

Any suggestions? Thank you for your responses!

+3


source to share


3 answers


The problem is with this expression:

m => m.Customer.PrimaryEngineer

      

DropDownListFor expects this lambda to give the property you are trying to set with this input control. In your case, this is not m.Customer.PrimaryEngineer

, but m.Customer.PrimaryEngineerId

, so this should fix:



m => m.Customer.PrimaryEngineerId

      

Also note that it is not necessary to set the Selected

list item property when using DropDownListFor, as this helper can display the selected item based on the provided model value.

+2


source


The best way I can see is to simply do it using this overload SelectList()

.

Replace your foreach loop code with this and you're good to go:

ViewBag.engineersListPrimary = new SelectList(engineers,
                                             "EmployeeId",
                                             "FirstName",
                                             model.Customer.PrimaryEngineerId);
return View(model);

      

and in the view:



@Html.DropDownListFor(m => m.Customer.PrimaryEngineer, 
                           ViewBag.engineersListPrimary as SelectList, 
                           new { style = "width:100%;"})

      

MSDN docs:

public SelectList(
    IEnumerable items,
    string dataValueField,
    string dataTextField,
    Object selectedValue
)

      

See SelectList class on MSDN

+1


source


Try something like this:

@Html.DropDownListFor(model => model.SelectedID, new SelectList(model.PrimaryEngineer, "Value", "Text"), "optionalLabel",  new { style = "width:100%;"})

      

0


source







All Articles