我如何获得SelectListItem而不是默认值为value = 0的SelectListItem?

时间:2019-01-26 19:08:08

标签: c# drop-down-menu asp.net-core-mvc

我在ViewComponent Default.cshtml中的工作日中有一个<select>,每天的关联值为0-6(星期日至星期六)。但是,我希望星期一被列为第一天,所以在我的ViewModel中,我有以下内容:

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 }
};

在我看来,我正在渲染下拉列表,如下所示:

<select asp-for="Weekday" class="form-control" asp-items="@Model.SelectableWeekdays">
</select>

我还尝试过手动添加选定的禁用选项:

<select asp-for="Weekday" class="form-control" asp-items="@Model.SelectableWeekdays">
    <option selected disabled>Please choose</option>
</select>

无论我尝试什么,所选选项始终为“星期日”,并且当天已设置属性selected="selected"

我也尝试添加

new SelectListItem { Text = "Please choose", Value = "99", Selected = true, Disabled = true },

在ViewModel中,并在我的视图中省略了手动选项,但这也不起作用。禁用的“请选择”选项位于列表的顶部,但是星期日仍然是选择的选项。

1 个答案:

答案 0 :(得分:2)

我认为问题在于基础模型的属性Weekday的价值。

如果将此属性的值设置为默认要选择的选项(在这种情况下为1),则控件将相应地呈现。