Create dropdown with search text box using select2 library in MVC Application.
Important Links for library:
<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></scritp>
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
CSHTML Code:
<div class="form-group">
<label>Employee Code</label>
<div class="form-group">
<select id="ddlemployeeList" class="dropdownAuto form-control">
</select>
@Html.Hidden("lblemployeeId")
</div>
<label>Employee Code</label>
<div class="form-group">
<select id="ddlemployeeList" class="dropdownAuto form-control">
</select>
@Html.Hidden("lblemployeeId")
</div>
</div>
JQuery Code
$(document).ready(function () {
$(".dropdownAuto").select2({
placeholder: "EMPLOYEE NAME",
allowClear: true
});
//-----------------------Get Employee List in dropdown list-----------------------------------------------
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/DotNetByPriyanshu/EmployeeList",
dataType: 'json',
success: function (Result) {
$("#ddlemployeeList").append($("<option></option>").val('').html(''));
$.each(Result, function (key, value) {
$("#ddlemployeeList").append($("<option></option>").val(value.id).html(value.label));
});
},
error: function (Result) {
Swal.fire({
icon: 'error',
title: 'Oops...',
text: 'Error on dropdown List ::' + Result
})
}
});
});
$(".dropdownAuto").select2({
placeholder: "EMPLOYEE NAME",
allowClear: true
});
//-----------------------Get Employee List in dropdown list-----------------------------------------------
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/DotNetByPriyanshu/EmployeeList",
dataType: 'json',
success: function (Result) {
$("#ddlemployeeList").append($("<option></option>").val('').html(''));
$.each(Result, function (key, value) {
$("#ddlemployeeList").append($("<option></option>").val(value.id).html(value.label));
});
},
error: function (Result) {
Swal.fire({
icon: 'error',
title: 'Oops...',
text: 'Error on dropdown List ::' + Result
})
}
});
});
Controller Code
public class DotNetByPriyanshuController : Controller
{
{
[HttpGet]
public ActionResult EmployeeList()
{
public ActionResult EmployeeList()
{
KeyValuePair keyValuePair = new KeyValuePair();
keyValuePair.id = 1;
keyValuePair.label = "Priyanshu Kumar";
keyValuePair.id = 1;
keyValuePair.label = "Priyanshu Kumar";
List<KeyValuePair> EmpList= new List<KeyValuePair>();
EmpList.Add(keyValuePair);
return Json(EmpList, JsonRequestBehavior.AllowGet);
}
}