如何从存储在 ViewBag 中的列表中获取值作为 select 元素中的选项(值)?

How to fetch value from a list stored in a ViewBag as options(value) in a select element?

我在 Viewbag 中有几个项目作为列表:

 var days = new List<SelectListItem>();
        days.Add(new SelectListItem
        {   Text = "Monday", Value = "Monday" });
        days.Add(new SelectListItem
        {   Text = "Tuesday", Value = "Tuesday" });
        days.Add(new SelectListItem
        {   Text = "Wednesday", Value = "Wednesday" });
        days.Add(new SelectListItem
        {   Text = "Thursday", Value = "Thursday" });
        days.Add(new SelectListItem
        {   Text = "Friday", Value = "Friday" });

        ViewBag.DayItems = days;


我可以使用脚手架期间生成的 html 助手轻松地将此值传递给视图 class:

<div class="form-group">
        @Html.LabelFor(model => model.Days, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
         @Html.DropDownListFor(model => model.Days, (List<SelectListItem>)ViewBag.DayItems, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Days, "", new { @class = "text-danger" })
        </div>
    </div>


现在我有一个 html select 元素:

<select>
    <option value="@Value=ViewBag.DayItems"></option>
</select>

,我想将 ViewBag 中的日子作为值传递。我应该如何包含 ViewBag.DayItems?

以下方法对我有用:

@Html.DropDownList("selectedDay", ViewBag.DayItems as IEnumerable<SelectListItem>)

一个相当经典的方法是:

<select>
    @{ 
        foreach (var day in ViewBag.DayItems as IEnumerable<SelectListItem>)
        {
            <option  value="@day.Value">@day.Text</option>
        }
    }
</select>

可能缺少可选标签,试试这个:

@Html.DropDownListFor(model => model.Days, (List<SelectListItem>)ViewBag.DayItems, "Select one", new { @class = "form-control" })

添加可选字符串 'Select one' 或任何您想要的资源。