0

I have this Razor dropdown that gets the info from the DB via ajax but the options that show on the dropdown don't get selected. How to make the dropdown options become selected on click?

I tried to implement the answer to a similar question but it didn't work:

select2 load data using ajax cannot select any option

This is what I have so far:

Ajax

 $(document).ready(function () {
        $.validator.addMethod("regxPhone", function (value, element, regexpr) {
            return regexpr.test(value);
        }),
        $.validator.addMethod("regxEmail", function (value) {
            return /^([\w!.%+\-])+@@([\w\-])+(?:\.[\w\-]+)+$/.test(value);
        }),
        $.validator.addMethod('validEmail', function (value, element, param) {
            return valiEmailAjax($("#Email").val());
        });



        $('#dropdown-employees').select2({
            minimumInputLength: 0,
            multiple: false,
            dropdownParent: $('#dropdown-email-for-select2'),
            ajax: {
                url: "/en/BOEmployeeAjax/GetEmployeesExcept",
                type: "POST",
                dataType: "json",
                data: function (params) {
                    return {
                        emplId: 0,
                        t: params.term
                    }
                },
                processResults: function (data, params) {
                    return { results: data }
                }
            },

            placeholder: window.selectAnotherSupervisor,
            escapeMarkup: function (markup) { return markup; },
            
        });

Razor dropdown

<div class="col-md-4 fieldSize4" id="dropdown-employees">
                @Html.DropDownListFor(x => x.Employee, new SelectList(new Dictionary<string, string>(), "Key", "Value"), @FXM.BO.Strings.T("ddl_select_option"), new { @class = "form-control select2-allow-clear", @placeholder = "Select Symbols" })
                <span class="help-block">
                    @FXM.BO.Strings.T("lbl_employee_description")
                </span>
            </div>

Code after 1st changes:

@model FXM.BO.ViewModels.NewAffiliateViewModel

@{
    ViewBag.Title = "CreateAffiliate";
    Layout = "~/Views/Shared/_LoggedInLayout.cshtml";
}

<h2>Create Affiliate</h2>


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4 class="hidden">NewAffiliateViewModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.AffiliateName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.AffiliateName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.AffiliateName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group" id="dropdown-email-for-select2">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
            </div>
        </div>

        @*<div class="form-group">
                @Html.LabelFor(model => model.Employee, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Employee, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Employee, "", new { @class = "text-danger" })
                </div>
            </div>*@

        @*<div class="form-group">
                @Html.LabelFor(model => model.MT4Group, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.MT4Group, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.MT4Group, "", new { @class = "text-danger" })
                </div>
            </div>*@

        <div class="form-group">
            <label class="control-label col-md-2">
                @FXM.BO.Strings.T("employeeName") <span class="required">
                    @***@
                </span>
            </label>

            @*<div class="col-md-4 fieldPositionCol4 select2-bootstrap-prepend">*@
            <div class="col-md-4 fieldSize4" id="dropdown-employees">
                @Html.DropDownListFor(x => x.Employee, new SelectList(new Dictionary<string, string>(), "Key", "Value"), @FXM.BO.Strings.T("ddl_select_option"), new { @class = "form-control select2-allow-clear", @placeholder = "Select Symbols" })
                <span class="help-block">
                    @FXM.BO.Strings.T("lbl_employee_description")
                </span>
            </div>
            @*<img id="tpLoader" src="~/Content/images/ajax-loader.gif" class="hidden" />*@
        </div>

        <div class="form-group">
            <label class="control-label col-md-2">
                @FXM.BO.Strings.T("lbl_Bo_TradAcc_PlatformGroup") <span class="required">
                    @***@
                </span>
            </label>
            @*<div class="col-md-4 fieldPositionCol4 select2-bootstrap-prepend">*@
            <div class="col-md-4 fieldSize4">
                @Html.DropDownListFor(x => x.MT4Group, new SelectList(new Dictionary<string, string>(), "Key", "Value"), @FXM.BO.Strings.T("ddl_select_option2"), new { @class = "form-control select2-allow-clear", @placeholder = "Select Symbols" })
                <span class="help-block">
                    @FXM.BO.Strings.T("platform_group_description")
                </span>
            </div>
            <img id="tpLoader" src="~/Content/images/ajax-loader.gif" class="hidden" />
        </div>
        @*Create button*@
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="button" value="Create" class="btn btn-default" id="create-affiliate-button" />
            </div>
        </div>
    </div>
}

@*<div>
        @Html.ActionLink("Back to List", "Index")
    </div>*@


<script type="text/javascript" src="/Scripts/CustomScripts/Common/form-helpers.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />



<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
    // document.ready function
    $(function () {
        refreshGroups();
        // selector has to be . for a class name and # for an ID
        $('#create-affiliate-button').click(function (e) {
            //e.preventDefault(); // prevent form from reloading page
            console.log("blahblahblah");
            //alert("hiii");

            var b = $("form").serialize();
            //var a = $("form").serializeArray();
            console.log("formvalues", b);

            $.ajax({
                url: "@Url.Action("CreateAffiliate", "AjaxUI")",
                type: "GET",
            dataType: "json",
            data: {
                newAffiliateViewModel : b
            },

                //error: function (jqXHR, exception) {
                //    failMessage();
                //}
            });
        });
    });

    function refreshGroups() {
        var pltf = "MT4_LIVE";
        var out = $('#MT4Group');
        if (pltf != null && pltf !== "") {
            $.ajax({
                url: '/' + window.currentLangCulture + '/BOLiveForms/GetPlatformGroupByFilter',
                data: {
                    platform: pltf, currency: "", withId : true
                },
                type: 'GET',
                beforeSend: function () {
                    $('#tpLoader').show();
                },
                complete: function () {
                    $('#tpLoader').hide();
                },
                success: function (data) {
                    populateDropDown(out, data);
                    //$('#recomandedGroup').show();
                }
            });
        } else {
            out.empty();
            out.append($('<option></option>').val('').html(window.defaultSelection));
        }
    }

    //GetEmployeesExcept - Method that populates the Dropdown for EmployeeName

    $(document).ready(function () {
        $.validator.addMethod("regxPhone", function (value, element, regexpr) {
            return regexpr.test(value);
        }),
        $.validator.addMethod("regxEmail", function (value) {
            return /^([\w!.%+\-])+@@([\w\-])+(?:\.[\w\-]+)+$/.test(value);
        }),
        $.validator.addMethod('validEmail', function (value, element, param) {
            return valiEmailAjax($("#Email").val());
        });
        var WithId = $('#dropdown-employees');
        if(WithId.length>0){
        
            var ajax_url = '/en/BOEmployeeAjax/GetEmployeesExcept';
            var $ajax = WithId;
            loadSelectData();
        }
    });

    function loadSelectData() {
        var cstoken = $('input[name="_token"]').val();
        $ajax.select2({
            ajax: {
                url: ajax_url,
                dataType: 'json',
            
                data: function (params, cstoken, page) {
                    return {
                        "_token": cstoken,
                        searchtxt: params.term, // search term
                        page: params.page
                    
                    };
                },
            
                processResults: function (data) {
                    var vh = [];
                    var obj = jQuery.parseJSON(data);
                
                    $.each(obj, function(key,value) {
                        var itemName = value.empname;
                        var itemId = value.id;
                        vh.push({id: itemId, text: itemName });
                    }); 
                    console.log(vh);
                    return {
                        results: vh,
                        pagination: {
                            more: true
                        }
                    }
                },

                placeholder: 'Search for a result',
                minimumInputLength: 1,
            }
        });
    }
</script>







Tom Sawyer
  • 11
  • 2

1 Answers1

1

Please change your select2 ajax code like.

Please change your select2 ajax code like.
 $(document).ready(function () {
        $.validator.addMethod("regxPhone", function (value, element, regexpr) {
            return regexpr.test(value);
        }),
        $.validator.addMethod("regxEmail", function (value) {
            return /^([\w!.%+\-])+@@([\w\-])+(?:\.[\w\-]+)+$/.test(value);
        }),
        $.validator.addMethod('validEmail', function (value, element, param) {
            return valiEmailAjax($("#Email").val());
        });
        var WithId = $('#dropdown-employees');
        if(WithId.length>0){
        
            var ajax_url = '/en/BOEmployeeAjax/GetEmployeesExcept';
            var $ajax = WithId;
            loadSelectData();
        }
 });
    
    function loadSelectData() {
    var cstoken = $('input[name="_token"]').val();
     $ajax.select2({
        ajax: {
            url: ajax_url,
             dataType: 'json',
            
            data: function (params, cstoken, page) {
                return {
                    "_token": cstoken,
                    searchtxt: params.term, // search term
                    page: params.page
                    
                };
             },
            
            processResults: function (data) {
                var vh = [];
                var obj = jQuery.parseJSON(data);
                
                $.each(obj, function(key,value) {
                    var itemName = value.empname;
                    var itemId = value.id;
                    vh.push({id: itemId, text: itemName });
                }); 
                    console.log(vh);
                return {
                    results: vh,
                    pagination: {
                        more: true
                      }
                  }
            },
            placeholder: 'Search for a result',
            minimumInputLength: 1,
        }
    });
    }
  • I appreciate your input, thank you. Your code fixed the size of the dropdown - now it has the same size and look as the other dropdowns in the page, which is great. The problem is that the dropdown doesn't receive data from the DB anymore. It doesn't get populated with options to select from, when I click on it. And of course I can't select anything to see if it gets selected. – Tom Sawyer Jul 06 '21 at 08:36