B. Clay Shannon B. Clay Shannon - 7 months ago 9
HTML Question

How can I set a select element's itemindex to -1?

I'm dynamically adding values to a select element in my View code like so in my View/.cshtml:

@model WebAppRptScheduler.Models.HomeModel
@using System.Data
@{
DataTable dtUnits = Model.Units as DataTable;
var units = from x in dtUnits.AsEnumerable()
select new
{
unit = x.Field<string>("unit")
};
.....
<select class="form-control, dropdown" name="unitsselect">
@foreach (var field in units)
{
<option id="selItem_@(field.unit)" value="@field.unit">@field.unit</option>
}
</select>
.....


The values are populating fine, but the first option in the select element is automatically being selected. How can I set it to -1 so that nothing is selected? Can I do it after the foreach loop above, or must I do it using javascript, or can I do it in a C# code-behind file?

Answer

Like this :

<select class="form-control, dropdown" name="unitsselect">
    <option disabled selected value> -- select an option -- </option>
    @foreach (var field in units)
    {
        <option id="selItem_@(field.unit)" value="@field.unit">@field.unit</option>
    }
</select>

-- select an option -- Will be displayed by default. But if you choose an option,you will not be able select it back

Source : default select option as blank

Comments