Search code examples
jqueryajaxasp.net-corerazor-pagesbootstrap-multiselect

How to render partial view via ajax with bootstrap multi-select control within the partial


Currently returning a partial view via ajax. The partial view returns to the page fine. All elements are shown except one, the bootstrap multi-select drop-down. I suspect that because the partial is being built server side, it has no reference to the bootstrap multi-select library. How can i get this partial to render the bootstrap multi-select dropdown.

Asp.net Core 2.2 app with razor pages. Using the bootstrap multi-select library by David Stutz, see link multi-select. I have got this working by not using the multi-select library, however that isn't an option as it leaves the entire UI looking horrible and out of flow.

I know for a fact that the drop-down does work as I have tried rendering this partial on its own without ajax on page-load, and have used the drop-down in many other areas of the app.

This is the element, and this is how I am applying the multi-select tool.

@Html.DropDownListFor(x => x.SelectedItemIds, Model.ItemList, new { @class = "selectpicker", @multiple = "true" })

I have also tried adding the following script to the partial (even though this wont work)

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap-select.min.js"></script>

Solution

  • Since you're loading your partial view via Ajax, that means your parent view has most likely already loaded. I'm guessing that you have a script section where you do something like;

    <!-- Initialize the selectlist plugin: -->
    <script type="text/javascript">
        $(document).ready(function() {
            $('#example').multiselect();
        });
    </script>`
    

    You can see it will only run once. On the $(document).ready() event.

    If you make changes after that, like dynamically injecting your partial view into the parent view, multi-select needs to be triggered again before it will work, because it's not monitoring your HTML.

    So when your Ajax call is complete, do $('#example').multiselect();