代码之家  ›  专栏  ›  技术社区  ›  theJ

更改选定值下拉列表C#

  •  0
  • theJ  · 技术社区  · 6 年前

    下午,

    我有两个下拉列表,ServiceName和GroupName。基本上,当ServiceName的值更改时,我希望GroupName的内容基于所选的值进行更新,这两个值都共享数据库中的ServiceId字段。

    但是,我不能动态地更改所选的值,我已经在1中硬编码并尝试使用Jquery进行更改,但没有效果。

    public IActionResult Create(string id)
    {
        ViewData["id"] = id;
    
        var list = new SelectList(_context.DatabaseService.Where(t => t.id == id).Select(i => i.Service), "ServiceId", "ServiceName", 1);
        var selected = list.SelectedValue.ToString();
    
        ViewData["GroupName"] = new SelectList(_context.ComponentGroups.Where(t => t.ServiceId == Int32.Parse(selected)), "GroupId", "GroupName");
        ViewData["ServiceName"] = list; 
    
        return View();
    }
    

    是否可以使所选变量等于“我的ServiceName”下拉列表中的活动项?

    1 回复  |  直到 6 年前
        1
  •  0
  •   theJ    6 年前

    我设法用这个解决方案的组合来解决这个问题 Ajax call to populate select list when another select list changes 这个解决方案 bind drop down list using jquery ajax on change of first ddl .

    我创建了一个新方法,它以JSON格式显示我的所有组

        public IActionResult GetGroupByService()
        {
            var grouping = _context.ComponentGroups;
            return Json(grouping);
        }
    

    然后在我的视图中,我使用JQuery从JSON数组返回的数据中填充一个空的select列表

    <script language="javascript" type="text/javascript">
    function GetGroup(_serviceId) {
        $.ajax({
            url: '@Url.Action("GetGroupByService", "Components")',
            data: { serviceId: _serviceId },
            cache: false,
            type: "POST",
            success: function (data) {
                var markup = "";
                for (var x = 0; x < data.length; x++) {
                    if (data[x].serviceId == _serviceId) {
                        markup += "<option value=" + data[x].groupId + ">" + data[x].groupName + "</option>";
                    }
                }
                $("#GroupId").html(markup).show();
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });
    }
    </script>
    

    这是我的精选名单

    <label asp-for="ServiceId" class="control-label">Service Name</label>
    <select asp-for="ServiceId" class="form-control" asp-items="ViewBag.ServiceName" onchange="javascript:GetGroup(this.value);">
    
    <label asp-for="GroupId" class="control-label">Group Name</label>
    <select asp-for="GroupId" name="GroupId" class="form-control"></select>