【问题标题】:Changing Dropdown SelectList when a different dropdownlist item is selected RAZOR选择不同的下拉列表项时更改下拉选择列表 RAZOR
【发布时间】:2014-08-21 17:21:24
【问题描述】:

我有一个包含公司列表的下拉列表,我还有另一个包含公司分支机构列表的下拉列表。我需要使分支下拉列表依赖于公司选定的项目。因此,当用户从下拉列表中选择 company1 时,分支下拉列表应将列表填充到 company1 中的分支。我不知道该怎么做。这是我的下拉菜单的样子:

            <tr>
                <td class="search-label">
                    @Html.Label("Company: ")
                </td>
                <td>
                    @Html.DropDownList("cono", (List<SelectListItem>)ViewBag.CompanyList)
                </td>
            </tr>
            <tr>
                <td class="search-label">
                    @Html.Label("Branch: ")
                </td>
                <td>
                    @Html.DropDownList("branch", (List<SelectListItem>)ViewBag.BranchList)
                </td>
            </tr>

这是我的操作:

    [HttpGet]
    public ActionResult Default()
    {
        var currentUserCono = GetCurrentUserCono();
        //Set the Viewbags to populate the drop down menus on the view
        if (Session["cono"] != null)
        {
            currentUserCono = (int)Session["cono"];
        }
        ViewBag.CompanyList = _selectListLib.GetCompanies(currentUserCono);
        ViewBag.BranchList = Session["branch"] != null ? _selectListLib.GetBranches(currentUserCono,(string)Session["branch"]) : _selectListLib.GetBranches(currentUserCono);
        ViewBag.StatusTypeList = Session["statustype"] != null ? _selectListLib.GetStatusTypes((bool)Session["statustype"]) : _selectListLib.GetStatusTypes();

        return View();
    }

【问题讨论】:

标签: jquery asp.net-mvc-4 razor selectlist


【解决方案1】:

你有两个(更多,但两个主要的)流行技术:

  • 创建一个以公司 ID 作为参数的操作 (JSONResult),返回分支,序列化为 JSON。然后使用 jQuery 通过绑定到的 $.getJSON 检索该列表 Company 下拉列表的 jQuery .change() 事件。然后你可以 遍历该 JSON 列表并将选项元素添加到分支 下拉列表。

或者

  • 创建一个以公司 ID 作为参数的操作 (PartialViewResult),它返回包含分支下拉列表的部分视图,其中填充了视图中的相关分支。使用 jQuery 的 .load() 加载该视图,再次绑定到 Company 下拉列表中的 jQuery .change() 事件。为此,您需要在分支周围的元素上使用 ID,以便将其定位为 $("#yourTDId").load("/Controller/Action/" + $("#cono")。 val())

这是完成您需要的最简单的两种方法。我希望这对您的应用有所帮助并祝您好运。

【讨论】:

    猜你喜欢
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 2016-08-03
    • 1970-01-01
    • 1970-01-01
    • 2014-09-04
    相关资源
    最近更新 更多