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?

1
  • 1
    i think you have to add empty value in collection in start so it will get selected or you can do this before loop <option value=""></option> Commented Apr 20, 2016 at 20:55

4 Answers 4

3

You could add a default option outside of the foreach :

<select class="form-control, dropdown" name="unitsselect"> //_________________________^ Remove this comma <option value="0" selected>Choose unit please</option> @foreach (var field in units) { <option id="selItem_@(field.unit)" value="@field.unit">@field.unit</option> } </select> 
Sign up to request clarification or add additional context in comments.

2 Comments

It works; but the comma is needed, otherwise the select appears below the label, which I want to be on the left.
comma isn't needed. class attribute is a space separated list of class names. just remove form-control,
2
+50

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

2

If you don't like virtual/empty elements in <select>. You can add single line of javascript in scripts section, and set ID of <select id="unitselect" ...> element

@section scripts { <script type="text/javascript"> document.getElementById("unitselect").selectedIndex = -1; ... 

1 Comment

Thanks; I may eventually use that, but for now the "reminder" entry is okay.
1

i think you have to add empty value in collection in start so it will get selected or you can do this before loop

<option value="0">Please select</option> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.