Search code examples
asp.net-mvcjquery-select2jquery-select2-4

@html.DropDown ASP MVC and Select2 multiselect


I have an @Html.DropDownList added to my view, the data for this dropdown is passed as a property in a ViewModel. How do I add Select2 Multiselect plugin onto this dropdownlist.

@Html.DropDownList("ValueId", new SelectList(item.Values, "Id", "Name"), new { @class = "values js-example-basic-multiple", @multiple ="multiple", @id="dropDown"}) | @Html.ActionLink("Delete", "Delete", new { id=item.Id })`

JQuery:

$('#dropDown').select2();

After Page is Rendered:

 `<select class="values js-example-basic-multiple" data-val="true" data-val-number="The field ValueId must be a number." data-val-required="The ValueId field is required." id="dropDown" multiple="multiple" name="ValueId"><option value="4">M</option>

8 Red `

Scripts:

`<script src="/Content/jquery-3.1.1.min.js"></script>`

<link href="/Content/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/select2/4.0.3/js/select2.min.js"></script>

UPDATE: I found the error. I was adding a new instance of JQuery to my page, and I forgot that my shared_layout page already has an instance of JQuery added.


Solution

  • Based on the information you have provided, there are really two options :

    • The jQuery library isn't being loaded or referenced.
    • jQuery (or select2) aren't "ready" by the time they are called.

    Since select2 depends on jQuery, you'll have to make sure that you are referencing it and that you are placing your necessary code within a document-ready block to ensure your dependencies are ready prior to being called :

    <!-- Your Example List here -->
    @Html.DropDownList("Foo", new SelectList(ViewBag.List), new { multiple = "true", id = "dropDown"})
    
    <!-- Example references (prior to closing </body> tag) -->
    <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
    <script>
         $(function(){
              $('#dropDown').select2();
         });
    </script>
    

    You can see a complete, and fully functional example using ASP.NET here.