如何设置一个选择元素的项目索引为-1? [英] How can I set a select element's itemindex to -1?

查看:120
本文介绍了如何设置一个选择元素的项目索引为-1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我动态地添加值到选择的元素在我看来,code,像这样在我看来/ .cshtml:

  @model WebAppRptScheduler.Models.HomeModel
@using System.Data这
@ {
    数据表dtUnits = Model.Units的数据表;
    变种单元从X =在dtUnits.AsEnumerable()
    新选择
    {
        单位= x.Field<串GT(单位)
    };
.....
    <选择类=形式的控制,下拉NAME =unitsselect>
        @foreach(以单位VAR场)
        {
           <选项ID =selItem _ @(field.unit)VALUE =@ field.unit> @ field.unit< /选项>
         }
    < /选择>
.....

中的值填充罚款,但被自动被选中在选择元素中的第一个选项。我怎么可以设置它,以便没有选定为-1?我能做到这一点上面的foreach循环之后,或者使用JavaScript它,我必须做的,或者我可以做到这一点在C#code隐藏文件?


解决方案

这样的:

 <选择类=形式的控制,下拉NAME =unitsselect>
    <选项禁用所选值> - 选择一个选项 - < /选项>
    @foreach(以单位VAR场)
    {
        <选项ID =selItem _ @(field.unit)VALUE =@ field.unit> @ field.unit< /选项>
    }
< /选择>


  

- 选择一个选项 - 将被默认显示。但是,如果你选择一个选项,你将无法选择它回来


来源:默认选择选项为空白

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?

解决方案

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

这篇关于如何设置一个选择元素的项目索引为-1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆