繁体   English   中英

使用jQuery绑定或重新加载选择2 drodown

[英]Bind Or Reload Select 2 drodown using jquery

我在我的Asp.net MVC应用程序之一中使用select2下拉列表。 我需要在不刷新页面的情况下在数据库中添加项目后绑定/重新加载下拉列表。 现在,我正在使用查看包绑定下拉菜单。

我具有使用单击按钮时的弹出窗口添加新项目的功能。 我想在数据库中添加新项目后再次重新加载/绑定。

HTML:

@Html.DropDownListFor(x => x.BuildingSectorId, new SelectList(ViewBag.BuildingSectors, "BuildingSectorId", "Name"), new { @class = "form-control select2 pull-left", @id = "dr_buildingsector" })
<button type="button" class="btn btn-default " onclick="CreateBuildingSectorDialog()"><i class="fa fa-plus"></i></button>

jQuery查询

var dropdown = $(".select2");
    if (dropdown != null)
        dropdown.select2({
            minimumResultsForSearch: -1,

        });

任何帮助将不胜感激。

您需要使用Ajax调用

$(document).ready(function () {
$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "CountryDetails.asmx/LoadCountry",
    data: "{}",
    dataType: "json",
    success: function (Result) {
           Result=Result.d;
        $.each(Result, function (key, value) {
            $("#ddlcountry").append($("<option></option>").val
            (value.CountryId).html(value.CountryName));
        });
      // Another way of writing
        //  for (var i = 0; i < Result.length; i++) {
        // $("#ddlcountry").append("<option value=" + Result[i].ID + ">" + 
        //     Result[i].Name + "</option>");
        //  }

      // One more way of writing
        // for (var i in Result) {
        //  $("#ddlcountry").append($("<option></option>").val(Result[i].ID).
        //   text(Result[i].Name));
        //  }

    },
    error: function (Result) {
        alert("Error");
    }
});

});

如果要重新加载下拉列表,请使用ajax调用和jquery加载数据。

$.ajax({
  type: "POST",
  url: "pullDataBase.php",
  success: function(dataget){
    console.log(dataget);
    var data2comboBox1 = JSON.parse(dataget);

    $('#comboBox1').select2({
      placeholder: "Something...",
      data: data2comboBox1,
      disabled : false
    });
    //console.log("current select");
    //console.log($('#comboBox1').val());
    //console.log($('#comboBox1 :selected').text());

  },
  error: function(jqXHR, textStatus, errorThrown){ alert('error ' + errorThrown);}
});

在网址中,您可以过滤结果

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM