How to searchable dropdownlist

Dondon510 221 Reputation points
2022-08-02T03:21:11.107+00:00

I have a dropdownlist to show the list of timezones, it shows correctly but how to add search function?

cshtml

 <div class="row">  
        <div class="col-6 mb-2">  
                 <label class="form-label" for="">Timezone</label>  
                  <div class="input-group input-group-merge">  
                          @Html.DropDownListFor(x => x.timeZone, Model.timeZones, new { @id="timeZones", @class= "form-select" });   
                   </div>  
                   <span asp-validation-for="timeZones" class="text-danger"></span>  
      </div>  
</div>  

class:

public SelectList timeZones { get; set; } = new SelectList(Helper.Get_TimeZones(), "Value", "Text");
public string timeZone { get; set; } = "";

Helper

 public static List<SelectListItem> Get_TimeZone() {  

        List<SelectListItem> list = new List<SelectListItem>();  

          
            ReadOnlyCollection<TimeZoneInfo> timeZones = TimeZoneInfo.GetSystemTimeZones();  
            list.Add(new SelectListItem() { Value = "", Text = "" });  

            foreach (TimeZoneInfo timeZone in timeZones)  
            {  
                list.Add(new SelectListItem() { Value = timeZone.Id, Text = timeZone.DisplayName });  
            }  
         
      }  
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,138 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,006 Reputation points Microsoft Vendor
    2022-08-02T07:06:27.707+00:00

    Hi @Dondon510 ,

    You can try to use the Select2 jQuery Plugin for implementing Searchable DropDownList.

    Based on your code and add the following scripts (View the source code: 227131-sourcecode.txt):

    227103-image.png

    Then, the output as below:

    227117-1.gif


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments

0 additional answers

Sort by: Most helpful