0

I'm working on a ASP .Net Core project where for the first time I'm using Select2.

I have one page where I'm passing the ID's that I need by ViewModel like this:

Controller:

public async Task<IActionResult> MyPage()
{
    var model = new MyViewModel()
    {
        selectedUSerId = 1,
        selectedEmployeeId =1
    };
    return View(model);
}

View:

    @model MyViewModel

     <select class="form-select" id="User" name="User" data-url="@Url.Action("MyUserAction","MyUserController")" data-placeholder="@Localizer["SelectUser"].Value">
      <option></option>
     </select>
     <select class="form-select" id="Employee" name="Employee" data-url="@Url.Action("MyEmployee","MyEmployeeController")" data-placeholder="@Localizer["SelectUser"].Value">
      <option></option>
     </select>



     @section Scripts{

        <script type="text/javascript">
            var userId = "@Model.selectedUSerId";
            var emplyeeId = "@Model.selectedEmployeeId";
            $(document).ready(function () {
           
                $('select').each(function () {
                    InitSelect2(this.id);

                    
                });

              if(userId){
                      $('#User').val(userId).trigger('change');
                     }

                     if(emplyeeId){
                      $('#User').val(emplyeeId).trigger('change');
                     }
            });
    
            function InitSelect2(selector, selectedId = 0) {
                var url = $("#" + selector).data('url');
                var placeholder = $("#" + selector).data('placeholder');
                const type = "POST";
                const dataType = "json";
                if (!url) {
                    console.error("Selector: " + selector + " Unspecified URL");
                    return;
                }
                if (placeholder === "") {
                    console.error("Selector: " + selector + " Unspecified Placeholder");
                    return;
                }
                try {
                    $("#" + selector).select2({
                        theme: "bootstrap-5",
                        width: $(this).data('width') ? $(this).data('width') : $(this).hasClass('w-100') ? '100%' : 'style',
                        placeholder: placeholder,
                        allowClear: true,
                        minimumInputLength: 3,
                        ajax: {
                            url: url,
                            type: type,
                            dataType: dataType,
                            delay: 250,
                            data: function (params) {
                                var query = {
                                    id: selectedId,
                                    searchFullName: params.term,
                                }
                                return query;
                            },
                            processResults: function (data) {
                                console.log(data)
                                return {
                                    results: data.results
                                };
                            },
                        }
                    })
                } catch (ex) {
                    console.error(ex);
                }
            }
        </script>
    }

So far it works perfectly.

But when I try to do:

$('#User').val(userId).trigger('change'); or
$('#Employee').val(emplyeeId ).trigger('change');

nothing happened.

I think its gonna work only when I retrieve the data the first time when I click the drop donw list, instead of doing it every time when it is clicked. In that way I will have the <option>s and I can use the jQuery to select the <option> by Id.

I don't like to follow this approach, becouse the data should be load and setted dynamically. Theres no another way to do it?

makaMa
  • 11
  • 3
  • You're trying to eat your pizza before it's been delivered. The ajax call takes time to run, but your code runs before this has completed. – freedomn-m Nov 08 '22 at 15:26
  • @freedomn-m I understand, but even if I try it from the browser console after the data is retrieved like this: `$('#User').val(1).trigger('change');` nothign happend – makaMa Nov 08 '22 at 15:32
  • Hi,is my answer helpful? – Yiyi You Nov 17 '22 at 09:29

1 Answers1

0

If you want to do something only when first time the selected value is changed,you can try to use a js variable,change the value of it when first time the selected value is changed.Here is a sample,only when first time the selected value is changed,alert(1) will be called.

 var UserCount = 0;
        var EmplyeeCount = 0;
        
        $('#User').change(function() {
            if (UserCount == 0) {
                UserCount++;
                alert(1);
            }
        });
         $('#Employee').change(function() {
            if (EmplyeeCount == 0) {
                EmplyeeCount++;
                alert(1);
            }
        });
Yiyi You
  • 16,875
  • 1
  • 10
  • 22