Установка начальных значений при загрузке с использованием Select2 с Ajax - PullRequest
0 голосов
/ 30 января 2019

У меня есть элементы управления select2, настроенные с помощью Ajax (только одна опция).Я использую Select2 на стороне сервера Ajax-источник с ASP.NET Web Forms.Я пытаюсь получить некоторые значения при загрузке страницы, я уже заполнил некоторые параметры из другого запроса ajax, но я не могу получить эти предварительно заполненные параметры, когда я нажимаю элемент select, однако, мой код для select2 приведен ниже:

Я уже пробовал это http://qaru.site/questions/165372/setting-initial-values-on-load-with-select2-with-ajax, это http://qaru.site/questions/69384/select2-400-initial-value-with-ajax и это Установка начальных значений при загрузке с помощью Select2 с Ajax

Код на стороне клиента(HTML & Javascript):

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Select2ServersideTest.aspx.cs" Inherits="Select2ServersideTest" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title></title>
   <link href="assets/select2/dist/css/select2.min.css" rel="stylesheet" />

   <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   <script type="text/javascript" src="assets/select2/dist/js/select2.full.min.js"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <select id="myselect2" style="width:460px;"></select>
    </div>
    </form>
    <script type="text/javascript">
        $(function () {

           var prefetchedData = [];

           $.ajax({
               type: "GET",
               url: "DataProcessor.aspx",
               data: "{ searchText: ''}",
               contentType: "application/json",
               dataType: "json",
               async: false,
               success: function (data) {
                  var dataReturned = data.items;

                  $.each(dataReturned, function (i, d) {
                     prefetchedData.push({ id: d.id, text: d.full_name });
                  });

               },
               error: function (xhr, status, e) { alert("Error occur while fetching items list : " + xhr.responseText); }
          }); // end: ajax



          $('#myselect2').select2({
              data: prefetchedData,
              placeholder: 'Search for item',
              ajax: {
                  url: "https://api.github.com/search/repositories",
                  contentType: "application/json",
                  dataType: "json",
                  delay: 250,
                  data: function (params) {
                     return {
                        q: params.term, // search term
                        page: params.page
                     };
                  },
                  processResults: function (data, params) {
                      params.page = params.page || 1;

                      return {
                         results: data.items,
                         pagination: {
                            more: (params.page * 30) < data.total_count
                         }
                      };
                  },
                  cache: true
             },

             escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
             minimumInputLength: 1,
             templateResult: formatRepo,
             templateSelection: formatRepoSelection,
             //initSelection: function (element, callback) {
             //    //var cdata = [];
             //    //$(element.val()).each(function () {
             //    //    cdata.push({ id: this, text: this });
             //    //});
             //    //console.log(element.val());
             //    callback(cdata);
             //}

          });

          //$('#myselect2').select2().val(1).trigger("change");

        });


        /* =========== Functions ============ */

       function formatRepo(repo) {
          if (repo.loading) {
              return repo.full_name;
          }

          var newOption = "<option value='" + repo.id + "'>" + repo.full_name + "</option>";

          return newOption;
       }

       function formatRepoSelection(repo) {
          console.log("format selection");
          return repo.full_name || repo.id;
       }

    </script>
   </body>
</html>

Мой код C # (DataProcessor.aspx):

protected void Page_Load(object sender, EventArgs e)
{
    ProcessAjaxRequest();
}

private void ProcessAjaxRequest()
{
     //execute the request based on search cretaria       
    if ((Request.QueryString["searchText"] != null))
    {
        string search = Request.QueryString["searchText"];
        GetAllItems(search);
    }
}

public void GetAllItems(string searchTerm = "")
{
    List<Item> itemList = new List<Item>();
    //Result item = new Result();

    Pagination pg = new Pagination();

    if (String.IsNullOrEmpty(searchTerm))
    {

        itemList.Add(new Item() { ItemID = 1, ItemName = "PHP Fundamentals" });
        itemList.Add(new Item() { ItemID = 2, ItemName = "Javascript for .NET Developers" });
        itemList.Add(new Item() { ItemID = 3, ItemName = "jQuery Essential Traing" });
        itemList.Add(new Item() { ItemID = 4, ItemName = "MySQL for Web Developers" });
        itemList.Add(new Item() { ItemID = 5, ItemName = "PHP for Web Developers" });
        itemList.Add(new Item() { ItemID = 6, ItemName = "jQuery for .NET Developers" });

    }
    else
    {

        itemList.Add(new Item() { ItemID = 1, ItemName = "PHP Fundamentals" });
        itemList.Add(new Item() { ItemID = 2, ItemName = "Javascript for .NET Developers" });
        itemList.Add(new Item() { ItemID = 3, ItemName = "jQuery Essential Traing" });
        itemList.Add(new Item() { ItemID = 4, ItemName = "MySQL for Web Developers" });
        itemList.Add(new Item() { ItemID = 5, ItemName = "PHP for Web Developers" });
        itemList.Add(new Item() { ItemID = 6, ItemName = "jQuery for .NET Developers" });
        itemList.Add(new Item() { ItemID = 7, ItemName = "C# Fundamentals" });
        itemList.Add(new Item() { ItemID = 8, ItemName = "Javascript for web Developers" });
        itemList.Add(new Item() { ItemID = 9, ItemName = "Angular 2 Essential Traing" });
        itemList.Add(new Item() { ItemID = 10, ItemName = "Nodejs for front-end Developers" });
        itemList.Add(new Item() { ItemID = 11, ItemName = "Laravel App Development" });
        itemList.Add(new Item() { ItemID = 12, ItemName = "jQuery for .NET Developers" });
        itemList.Add(new Item() { ItemID = 13, ItemName = "PHP Fundamentals" });
        itemList.Add(new Item() { ItemID = 14, ItemName = "Javascript for .NET Developers" });
        itemList.Add(new Item() { ItemID = 15, ItemName = "jQuery Essential Traing" });
        itemList.Add(new Item() { ItemID = 16, ItemName = "MySQL for Web Developers" });
        itemList.Add(new Item() { ItemID = 17, ItemName = "PHP for Web Developers" });
        itemList.Add(new Item() { ItemID = 18, ItemName = "ExpressJs for .NET Developers" });

    }

    pg.more = true;

    var serializer = new JavaScriptSerializer();

    //int total_count = 200;
    //bool incomplete_results = true;

    // send response using json
    string json = serializer.Serialize(new { items = itemList });

    Response.Write(json);
    //return json;
}
...