Reputation: 1602
I have a <select>
for weekdays in a ViewComponent Default.cshtml, each day with the associated values of 0-6 (Sunday to Saturday). However, I want Monday to be listed as the first day, so in my ViewModel, I have this:
public List<SelectListItem> SelectableWeekdays => new List<SelectListItem>
{
new SelectListItem { Text = "Monday", Value = "1", Selected = true },
new SelectListItem { Text = "Tuesday", Value = "2", Selected = false },
new SelectListItem { Text = "Wednesday", Value = "3", Selected = false },
new SelectListItem { Text = "Thursday", Value = "4", Selected = false },
new SelectListItem { Text = "Friday", Value = "5", Selected = false },
new SelectListItem { Text = "Saturday", Value = "6", Selected = false },
new SelectListItem { Text = "Sunday", Value = "0", Selected = false }
};
In my view, I'm rendering the dropdown like this:
<select asp-for="Weekday" class="form-control" asp-items="@Model.SelectableWeekdays">
</select>
I have also tried adding a selected, disabled option manually:
<select asp-for="Weekday" class="form-control" asp-items="@Model.SelectableWeekdays">
<option selected disabled>Please choose</option>
</select>
No matter what I have been trying, the selected option is always "Sunday" with the attribute selected="selected"
being set for that day.
I have also tried adding
new SelectListItem { Text = "Please choose", Value = "99", Selected = true, Disabled = true },
in the ViewModel, and omitting the manual option in my view, but that didn't work either. The disabled "Please choose"-option was there at the top of the list, but Sunday was still the selected option.
Upvotes: 0
Views: 82
Reputation: 7783
I believe the issue is the value of the underlying model's property Weekday
.
If you set the value of this property to the option you want selected by default (1
in this case), the control will be rendered accordingly.
Upvotes: 2