skip to Main Content

I am trying to apply the select2 jQuery function in a dropdownlist in my ASP.NET MVC view but I am stuck can anyone help me in this regard Thanks in advance.

Here is my view

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<script>
    $(document).ready(function () {
         $("#WorkerId").select2({ multiple: true }); 
    });
</script>

<div class="form-group workerDiv Show" style="font-weight:bolder; color:white">
    <label>Select Workers</label><br />
    <div class="col-md-10">
        <div class="u-form-group">
            @Html.DropDownList("WorkerId", new SelectList(Enumerable.Empty<SelectListItem>()), "Select Cateogry", htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(m => m.WorkerId, "", new { @class = "text-danger" })
        </div>
    </div>
</div>

I am also using ajax call for filling this dropdownlist which is here…

<script>
    function FillWorker() {
        var skill = $('#SkillId').val();

        $.ajax({
            url: '/Order/FillWorker?skill=' + skill,
            type: "GET",
            dataType: "JSON",
            data: { SkillId: skill },
            success: function (workers) {
                $("#WorkerId").html(""); // clear before appending new list

                $.each(workers, function (i, workers) {
                    $("#WorkerId").append(
                        $('<option></option>').val(workers.Value).html(workers.Text));
                });
            }
        });
    };
</script>

2

Answers


  1. Chosen as BEST ANSWER

    I resolve this issue through this way that in my layout.cshtml there are multiple scripts are running so I just remove them my issue is resolve


  2. Please replace your code with following one. because in your case you set select option in document.ready event at this time maybe your dropdown list not populated. so select2 not working. so setTimeout need or write after your dropdown populated     
    
    setTimeout(function () { $("#WorkerId").select2(); }, 1000);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search