Reputation: 1117
I'm having problems trying to get a preselected value to work. I've tried to include Selected in the SelectListItem but it doesn't pre-select. Any clues as to why it's not matching up? Thanks for any help.
RetailerId is int. (it's not defined as enumerable)
Retailer is an enum, for example:
public enum Retailer
{
Sears = 10,
Macys = 20
}
Here is the View code :
@Html.DropDownListFor(x => x.RetailerId,
Enum.GetValues(typeof(Retailer)).Cast<Retailer>()
.OrderBy(o => o.GetDescription())
.Select(o => new SelectListItem() { Text = o.GetDescription(), Value = o.ToString(), Selected = (o.ToInt() == Model.RetailerId) }),
new { @data_placeholder = "Select Retailer", @class = "form-control" })
Upvotes: 1
Views: 78
Reputation:
Your generating a collection of SelectListItem
where the Value
is either "Sears" or "Macys" which cannot be bound to property RetailerId
which is an int
.
Note that the Selected
property of SelectListItem
is ignored when binding to a model property. Internally the method sets the Selected
property based on the value of the property your binding to, and since its an int
, it does not match any of your options values and the first option is selected because something has to be.
You can make this work by modifying the .Select
clause to
.Select(o => new SelectListItem() { Text = o.GetDescription(), Value = ((int)o).ToString() }),
Alternatively, change the model property to
public Retailer RetailerId { get; set; }
an the .Select
clause to
.Select(o => new SelectListItem() { Text = o.GetDescription(), Value = o.ToString() }),
Upvotes: 3