javascript - 带有 json 数据并选择的 MVC 下拉列表

标签 javascript json ajax asp.net-mvc jquery-chosen

我正在尝试使用第二个列表上的 jsonResult 数据填充下拉列表 关于更改事件。效果很好。但我也想在该列表上使用选择,并且该列表为空。看起来 selected 没有获取列表更新。我对此很陌生,所以请帮忙

First list:
 <div class="col-md-10">
     @Html.DropDownList("tipopreme_TipOpremeID", null, htmlAttributes: new { @class = "form-control", @onchange = "PopuniDropOpreme()" })
 </div> 

第二个列表:

 @Html.DropDownListFor(x => x.ModelOpreme_ModelOpremeID, new SelectList(Enumerable.Empty<SelectListItem>()))

Controller :

    public JsonResult getOpremaPoTipu(int? tipid)
    {
        List<SelectListItem> lista = new List<SelectListItem>();
        if (tipid != null)
        {
            foreach (var item in db.ModelOpremes.Where(x=>x.TipOpreme_TipOpremeID==tipid))
            {
                lista.Add(new SelectListItem { Text = item.PunNaziv, Value = item.ModelOpremeID.ToString()});
            }               
        }
        else
        {
            foreach (var item in db.ModelOpremes)
            {
                lista.Add(new SelectListItem { Text = item.PunNaziv, Value = item.ModelOpremeID.ToString() });
            }
        }
        return Json(lista, JsonRequestBehavior.AllowGet);
    }

Script:

    @section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/chosen.jquery.min.js"></script>
<link href="~/Content/chosen.min.css" rel="stylesheet" />
<script type="text/javascript">
    $(".chzn-select").chosen();
    $("#ModelOpreme_ModelOpremeID").chosen(); 

    function PopuniDropOpreme() {
        var tip = $("#tipopreme_TipOpremeID").val();
        $.ajax({

            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: "/Opremas/getopremapoTipu?selectedValue=" + tip,
            data: "{}",
            dataType: "Json",
            success: function (data) {
                

            
                $('.ddlProjectvalue').find('option').remove();

                  
                $(data).each(function (index, item) { 
           

                    $("#ModelOpreme_ModelOpremeID").append($('<option></option>').val(item.Value).html(item.Text));
                });
                $("ModelOpreme_ModelOpremeID").chosen("destroy").chosen();
            },
            error: function ajaxError(response) {
                alert(response.status + ' ' + response.statusText);
            }
        });
    }   
    
</script>

最佳答案

您的代码中有一些错误:

- url: "/Opremas/getopremapoTipu?selectedValue=" + tip, //wrong param name
- $('.ddlProjectvalue').find('option').remove(); //wrong id

它们应该是:

- url: "/Opremas/getopremapoTipu?tipid=" + tip
- $('#ModelOpreme_ModelOpremeID').find('option').remove();

您可以按照我的示例进行操作。希望对您有所帮助,我的 friend !

public class Test
    {
        public int Id { get; set; }
        public string Value { get; set; }
    }
public JsonResult GetData(int? selectedValue)
        {
            List<SelectListItem> lista = new List<SelectListItem>();
            if (selectedValue != null)
            {
                foreach (var item in Data().Where(t=>t.Id == selectedValue))
                {
                    lista.Add(new SelectListItem
                    {
                        Text = item.Id.ToString(),
                        Value = item.Value
                    });
                }
            }
            else
            {
                foreach (var item in Data())
                {
                    lista.Add(new SelectListItem { Text = item.Id.ToString(), Value = item.Value.ToString() });
                }
            }
            return Json(lista, JsonRequestBehavior.AllowGet);
        }

        private List<Test> Data()
        {
            var data = new List<Test>
            {
                new Test{Id = 1, Value = "A1"},
                new Test{Id = 1, Value = "A2"},
                new Test{Id = 1, Value = "A3"},
                new Test{Id = 1, Value = "A4"},

                new Test{Id = 2, Value = "B1"},
                new Test{Id = 3, Value = "C1"},
                new Test{Id = 4, Value = "D1"},
            };
            return data;
        }

View 中的代码:

@{
    ViewBag.Title = "About";    
}

<html>
<head>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
    <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
    <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.css">
</head>
<body style="margin-top:50px;">

    <script type="text/javascript">
        $(function () {
            $(".chzn-select").chosen();
            $("#ModelOpreme_ModelOpremeID").chosen();
            $(".chzn-select").chosen().change(function () {
                var id = $(this).val();
                $.ajax({

                    type: "GET",
                    contentType: "application/json; charset=utf-8",
                    url: "/Home/GetData?selectedValue=" + id,
                    data: "{}",
                    dataType: "Json",
                    success: function (data) {

                        $('#ModelOpreme_ModelOpremeID').find('option').remove();                        
                        $(data).each(function (index, item) {
                            $("#ModelOpreme_ModelOpremeID").append($('<option></option>').val(item.Text).html(item.Value));
                        });
                        $("#ModelOpreme_ModelOpremeID").chosen("destroy").chosen();
                    },
                    error: function ajaxError(response) {
                        alert(response.status + ' ' + response.statusText);
                    }
                });
            });
        });
    </script>

    <select class="chzn-select" name="faculty" style="width:200px; margin:10%;">
        <option value="1">A</option>
        <option value="2">B</option>
        <option value="3">C</option>
        <option value="4">D</option>
    </select>
    <br />
    <select id="ModelOpreme_ModelOpremeID"  style="width:200px; ">
    </select>
</body>
</html>

关于javascript - 带有 json 数据并选择的 MVC 下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44606181/

相关文章:

javascript - 遍历表单上的多个输入字段并推送到 firebase

ios - NSURLConnection 失败,没有错误

javascript - 带有顶级数组的 Handlebars.js 模板

javascript - 如何解决 jQuery 冲突?

javascript - jQuery 获取 HTML 值

javascript - ImageMagick 比较 : exit code 1 when spawned from Node. js,但从命令行运行时退出代码 0

javascript - 需要 firefox/IE designMode 引用

php - 来自带链接的 JSON 的 AutoSuggest

javascript - 使用 node.js 进行基本 Ajax 发送/接收

javascript - jQuery UI 自动完成 : Only allow selected valued from suggested list