Unable To Make A Dropdown List Searchable
I have a dropdown list in my view page but it is not a searchable dropdown, this is how I populate dropdown values public ActionResult SpecialOrderSummary(int? id) {
Solution 1:
Asp.Net doesn't support searchable dropdowns by default. You can use select2 dropdown which is a wrapper around normal dropdown.
Try this:
Step 1: Import the necessary css and script:
<!-- Bootstrap css--><linkrel="stylesheet"href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css"><!-- Select2 css--><linkhref="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css"rel="stylesheet" />
Step 2: Your Actual Dropdown
@Html.DropDownList("PartID", null, "-- Select --", htmlAttributes: new { @class = "form-control chosen-select Part-select" })
Step 3: Bind the searchable select2 dropdown on page load using jquery
<!-- JQuery script--><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><!-- Select2 script--><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
$(document).ready(function(){
$('.chosen-select').select2({ // .chosen-select is class name(from your dropdown)
placeholder: "Select"
});
});
Sample output:
NOTES:
- The order of scripts is VERY important. Mention their order as I have mentioned here.
- Best practice is to mention the style links above(within head tag) and scripts below(within your body tag)
- If you get stuck here is the link: Codepen-Searchable Dropdown demo
Post a Comment for "Unable To Make A Dropdown List Searchable"