【问题标题】:How can I get json data from Action method and place it in select list using jQuery如何从 Action 方法获取 json 数据并使用 jQuery 将其放置在选择列表中
【发布时间】:2020-04-28 04:52:29
【问题描述】:

实际上我的问题是我有一个操作方法将返回 JSON(国家列表),我想将该数据绑定到引导选择列表,我找到了几个代码 sn-ps 但它们实际上显示了完整的国家列表.

【问题讨论】:

    标签: jquery asp.net asp.net-mvc bootstrap-4


    【解决方案1】:

    通过这种方式,您可以使用 jsonResult 绑定下拉列表。

    In your controller
    
    public ActionResult getCountry()  
        {  
            DatabaseEntities db = new DatabaseEntities();  
            return Json(db.Country.Select(x => new  
            {  
                CountryID = x.CountryID,  
                CountryName = x.CountryName  
            }).ToList(), JsonRequestBehavior.AllowGet);  
        }  
    

    在你的 javascript 中

    $(document).ready(function () {  
       $.ajax({  
           type: "GET",  
           url: "/Users/getCountry",  
           data: "{}",  
           success: function (data) {  
               var s = '<option value="-1">Please Select a Country</option>';  
               for (var i = 0; i < data.length; i++) {  
                   s += '<option value="' + data[i].CountryID + '">' + 
               data[i].CountryName + '</option>';  
               }  
               $("#CountryDropdown").html(s);  
           }  
       });  
    });  
    

    在你的视野中

    <form id="myForm">  
        <label for="CountryDropdown"><b>Departments</b></label>  
        <select class="form-control" id="CountryDropdown" 
      name="CountryDropdown"></select>  
    </form>  
    

    【讨论】:

    • 您好,先生,我有一个这种类型的 JSON - ["Afghanistan","Albania","Algeria","Argentina","Armenia"]
    • @DONEPUDIRAJESH,如果您得到的响应没有 ID,那么您如何将其绑定到您的下拉列表
    • 只需使用data[i] 作为您的选项值和文本。这应该可以解决问题
    • 这也不是数据绑定,您只是使用 ajax 调用的结果创建或更新选择列表
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多