Bootstrap-selectpicker to a default value without using JS or jQuery

Viewed 340

I'm mixing HTML and C# and I want to set the default selected value from a selectpicker. As I load a lot of data that contain each a selectpicker, I need to select the right option directly when the page is loading and not afterwards which will cost me time (using document ready, trigger the selection for each of the data showed).

Here's what I'm trying for the moment:

<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>

As you can see I try to make it work with this: selected=@(item.PaymentStatus == 2 ? "selected" : "") but the value returned true but it's not selected, it's always the first option that is selected.

2 Answers

Try this instead of empty string, use null:

 <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>

Thats because you only need the selected not selected="selected" or selected="true" in your <option> to actually make it selected. You should try:

 <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>
Related