在不使用JS或jQuery的情况下,将selectpicker引导到默认值



我正在混合HTML和C#,我想从selectpicker中设置默认的选定值。由于我加载了很多数据,每个数据都包含一个selectpicker,所以我需要在加载页面时直接选择正确的选项,而不是在加载之后,这将花费我的时间(使用文档就绪,触发显示的每个数据的选择(。

以下是我目前正在尝试的内容:

<select id="PayStatus" data-key="@item.CandidateId" class="selectpicker gw-bs-small w-100">
<option value="0" selected=@(item.PaymentStatus == 0 ? "selected" : "") data-content="<span class='badge badge-red-dark-500 text-white label-important'><i class='icon-cross mr-1'></i>InvoiceOpen</span>"></option>
<option value="1" selected=@(item.PaymentStatus == 1 ? "selected" : "") data-content="<span class='badge badge-byline-300 text-green'>FreeDevelopment</span>">FreeDevelopment</option>
<option value="2" selected=@(item.PaymentStatus == 2 ? "selected" : "") data-content="<span class='badge badge-green-500 text-white'><i class='icon-check mr-></i></span>
</select>

正如你所看到的,我试图让它与以下内容一起工作:selected=@(item.PaymentStatus == 2 ? "selected" : ""),但值返回true,但它没有被选中,它总是第一个被选中的选项。

尝试使用空字符串,而不是空字符串:

<select id="PayStatus" data-key="@item.CandidateId" class="selectpicker gw-bs-small w-100">
<option value="0" selected=@(item.PaymentStatus == 0 ? "selected" : null) data-content="<span class='badge badge-red-dark-500 text-white label-important'><i class='icon-cross mr-1'></i>InvoiceOpen</span>"></option>
<option value="1" selected=@(item.PaymentStatus == 1 ? "selected" : null) data-content="<span class='badge badge-byline-300 text-green'>FreeDevelopment</span>">FreeDevelopment</option>
<option value="2" selected=@(item.PaymentStatus == 2 ? "selected" : null) data-content="<span class='badge badge-green-500 text-white'><i class='icon-check mr-1'></i>InvoicePaid</span>">InvoicePaid</option>
</select>

这是因为您只需要<option>中的selected,而不需要selected="selected"selected="true"就可以真正选中它。你应该试试:

<select id="PayStatus" data-key="@item.CandidateId" class="selectpicker gw-bs-small w-100">
<option value="0" @(item.PaymentStatus == 0 ? "selected" : "") data-content="<span class='badge badge-red-dark-500 text-white label-important'><i class='icon-cross mr-1'></i>InvoiceOpen</span>"></option>
<option value="1" @(item.PaymentStatus == 1 ? "selected" : "") data-content="<span class='badge badge-byline-300 text-green'>FreeDevelopment</span>">FreeDevelopment</option>
<option value="2" @(item.PaymentStatus == 2 ? "selected" : "") data-content="<span class='badge badge-green-500 text-white'><i class='icon-check mr-1'></i>InvoicePaid</span>">InvoicePaid</option>
</select>

最新更新