我在我的View / .cshtml中动态地将值添加到我的View代码中的select元素:
@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>
.....
值正在填充,但是会自动选择select元素中的第一个选项。如何将其设置为-1以便不选择任何内容?我可以在上面的foreach循环后执行此操作,还是必须使用javascript执行此操作,还是可以在C#代码隐藏文件中执行此操作?
答案 0 :(得分:3)
您可以在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>
答案 1 :(得分:2)
像这样:
<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 --
默认显示。但是如果你选择一个选项,你将无法选择它
答案 2 :(得分:2)
如果您不喜欢&lt; select&gt;中的虚拟/空元素。您可以在脚本部分添加单行javascript,并设置ID&lt; select id =&#34; unitselect&#34; ...&GT;元件
@section scripts
{
<script type="text/javascript">
document.getElementById("unitselect").selectedIndex = -1;
...
答案 3 :(得分:1)
我认为你必须在开始时在集合中添加空值,这样它才会被选中,或者你可以在循环之前执行此操作
<option value="0">Please select</option>