简体   繁体   English

选择了 json 值的选择列表项

[英]Selectlist item whith json value selected

I am trying to create a one that is filled with elements that I send to the view through a json result, but I have problems to indicate the seleted value which comes from the json.我正在尝试创建一个充满元素的元素,这些元素通过 json 结果发送到视图,但我无法指出来自 json 的选定值。

Method:方法:

        [HttpGet]
    public JsonResult GetProductJson()
    {
        var list = new List<SelectListItem>
        {
            new SelectListItem { Value = "1", Text = "Aron" },
            new SelectListItem { Value = "2", Text = "Bob" },
            new SelectListItem { Value = "3", Text = "Charlie", Selected = true},
            new SelectListItem { Value = "4", Text = "David" }
        };

        return Json(list, JsonRequestBehavior.AllowGet);
    }

View:看法:

        <select id="MyList"></select>

    <script>
        fetch("@Url.Content("~/Home/GetProductJson")")
            .then(function(result) {
                if (result.ok) {
                    return result.json();
                }
            })
            .then(function(data) {
                console.log(data);
                $('#MyList').empty();
                $.each(data,function(i,value){
                    $('#MyList').append($('<option/>')
                        .val(value.Value)
                        .text(value.Text)
                        //.selected(value.Selected) == true ? 'Selected': ''
                           )
                })
                });
    </script>

Just change your code to:只需将您的代码更改为:

$.each(data,function(i,value){
                    $('#MyList').append($('<option/>')
                        .val(value.value)
                        .text(value.text)
                        .attr("selected", value.selected)
                           )
                })

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

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