I have a dropdownlist that will not display the selected value correctly. It does have the correct elements in it, has the correct text and values being used but there just doesn’t seem to be a way to make it actually select the correct value.
What I’ve got is:
public class StateViewModel {
public string Name { get; set; }
public string Abbr { get; set; }
}
public class ChangeAddressViewModel {
//edited down to what's needed
public StateViewModel StateViewModel { get; set; }
public IEnumerable<StateViewModel> StateViewModels { get; set; }
}
What I’ve tried:
@Html.DropDownListFor(model => model.StateViewModel
, Model.StateViewModels.Select(x => new SelectListItem {
Text = x.Name,
Value = x.Abbr,
Selected = x.Abbr == Model.StateViewModel.Abbr
})
, @Resource.SelectState)
//i've stepped through the lambda above and the expression
//x.Abbr == Model.StateViewModel.Abbr
//did evaluate to true for one of the iterations
@Html.DropDownListFor(model => model.StateViewModel
, new SelectList(Model.StateViewModels
, "Abbr"
, "Name"
, Model.StateViewModel.Abbr)
, @Resource.SelectState)
I see you are specifying a new SelectList :
this will render a new instance of the list, not the one you were passing in!Hence you will not have a selected value.
Try setting it to :
And in your Controller/ViewModel, populate the SelectList as shown below.I wrote my own example as it was easier. below is the code for the Controller, within the ActionResult :
Your ViewModel would look like this :
I’m assuming this was your question, and that you didnt want to actually have a new list, and also select a value within that list as a default.
If that was the case, try this:
I think your closing brace was in the wrong position !