TechJhola TechJhola - 3 months ago 15
ASP.NET (C#) Question

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

I have few items in Viewbag as a list:

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;



I can easily pass this value to the view class using html helper generated during scaffolding in this way:

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




Now I have a html select element:

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


,where I want to pass the days from ViewBag as value. How should I include ViewBag.DayItems?

Answer

The below approach works for me:

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

A rather classical approach would be:

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