Fill Select2 dropdown box from database in MVC 4

后端 未结 3 1562
[愿得一人]
[愿得一人] 2020-12-29 00:08

I need help writing the jquery/ajax to fill a Select2 dropdown box.

For those who don\'t know what Select2 is, it is a javascript extension to provide Twitter Bo

3条回答
  •  甜味超标
    2020-12-29 00:23

    Solved! Finally.

    The full jquery is below, what was needed were two functions to format the returned results from the controller. This is because the dropbox needs some html markup to be wrapped around the results in order to be able to display them.

    Also contractID was needed as an attribute in the controller as without it results were shown in the dropdown, but they could not be selected.

    $("#contractName").select2({
        placeholder: "Type to find a Contract",
        allowClear: true,
        minimumInputLength: 2,
        ajax: {
            cache: false,
            dataType: "json",
            type: "GET",
            url: "@Url.Action("FetchContracts", "Leads")",
            data: function(searchTerm){
                return { query: searchTerm };
            },
            results: function(data){
                return { results: data };
            }
        },
        formatResult: contractFormatResult,
        formatSelection: contractFormatSelection,
        escapeMarkup: function (m) { return m; }
    });
    
    
    function contractFormatResult(contract) {
        var markup = "";
        if (contract.name !== undefined) {
            markup += "
    " + contract.name + "
    "; } markup += "
    " return markup; } function contractFormatSelection(contract) { return contract.name; }

提交回复
热议问题