Setting a default selected value into a dropdown list

585 Views Asked by At

I'm trying to set a default value selected on the list generated from the viewbag. The default selected item on the list is the first item(it is an empty item ""). Anyone that could help. Code in .cshtml file : @Html.EditorFor(x => x.TimeZoneId, "Generic_DropDownList", new { Items = ViewBag.TimeZones, InputClass = "InvisibleField", HideFormUnit = true, HideLabel = true })

1

There are 1 best solutions below

4
Yiyi You On

If you want to set a default selected value,try to use the following code:

<select asp-for="TimeZoneId">
    @foreach(var item in ViewBag.TimeZones)
    {
        <option>Generic_DropDownList</option>
        if (item.Value == "{Value}")
        {          
            <option [email protected] selected>@item.Text</option>
        }
        else
        {
            <option [email protected]>@item.Text</option>
        }
    }

</select>