【问题标题】:Dropdown with categories and subcategories带有类别和子类别的下拉菜单
【发布时间】:2015-07-14 16:59:28
【问题描述】:

我在 SQL 中有 2 个表。

Category_Tbl:

ID  Categories 
1   Projects 
2   Residential 
3   Commercial

SubCategory_Tbl:

ID  CATID   Subcategories
1   1   Residential  Projects
2   1   Commercial Projects
3   2   Residential Apartment
4   2   Independent/Builder Floor
5   2   Independent House/Villa
6   2   Residential Land
7   2   Studio Apartment
8   2   Farm House
9   2   Serviced Apartments
10  3   Commercial Shops
11  3   Commercial Showrooms
12  3   Commercial Office/Space
13  3   Commercial Land/Inst. Land

我想用复选框将所有类别及其子类别绑定到下拉列表中。像

我在 Google 上搜索过,但没有任何有价值的结果。

【问题讨论】:

  • 将主下拉列表的数据源设置为数据访问返回的类别集合。当在主下拉列表中调用 selected index changed 事件时,将调用以检索与主类别 ID 对应的子类别,该 ID 等于主下拉列表的选定值,并且该集合成为辅助下拉集合。

标签: c# jquery sql asp.net


【解决方案1】:

不要插入另一家公司,但我(在很多情况下)使用 Kendo UI 树视图来处理这类事情。有点为你做的工作。这取自他们的基本 HTML5 演示(此处未使用 html5)。

http://demos.telerik.com/kendo-ui/treeview/checkboxes

这是一个您可以查看的小提琴,但实际上只是设置您的数据源。我可能会通过 ajax(或序列化 json)加载数据源,以简化创建树视图的方式。

http://jsfiddle.net/ztc4ma52/3/

通过一些小工作,您可以稍微清理一下样式,使其看起来与您所做的非常相似。

小提琴代码示例。

$(function () {
    $('#list1').kendoTreeView({

        checkboxes: {
            checkChildren: true
        },
        check: function (e) {
            e.preventDefault();

        },
        dataSource: [{
            catid: 1,
            text: "Projects",
            expanded: true,
            items: [{
                subcatid: 2,
                catid: 1,
                text: "Residential Projects"
            }, {
                subcatid: 3,
                catid: 1,
                text: "Commercial Projects"
            }],
        }, {
            catid: 2,
            text: "Residential",
            expanded: true,
            items: [{
                subcatid: 3,
                catid: 2,
                text: 'Residential Apartment'
            }, {
                subcatid: 4,
                catid: 2,
                text: 'Independent/Builder Floor'
            }, {
                subcatid: 5,
                catid: 2,
                text: 'Independent House / Villa'
            }, {
                subcatid: 6,
                catid: 2,
                text: 'Residential Land'
            }, {
                subcatid: 7,
                catid: 2,
                text: 'Studio Apartment'
            }, {
                subcatid: 8,
                catid: 2,
                text: 'Farm House'
            }, {
                subcatid: 9,
                catid: 2,
                text: 'Serviced Apartments'
            }]
        }, {
            catid: 3,
            text: "Commercial",
            expanded: true,
            items: [{
                subcatid: 10,
                catid: 3,
                text: 'Commercial Shops'
            }, {
                subcatid: 11,
                catid: 3,
                text: 'Commercial Showrooms'
            }, {
                subcatid: 11,
                catid: 3,
                text: 'Commercial Office/Space'
            }, {
                subcatid: 11,
                catid: 3,
                text: 'Commercial Land/Inst. Land'
            }]
        }]
    });
});

根据评论。如果您想直接从您的 SQL 服务器绑定,您可以使用简单的查询来管理它。如果您使用的是Asp.Net Webforms(我认为您是),我们可以使用Newtonsoft JSON.Net 作弊并返回序列化的JSON 数据,该数据预装在初始应用程序http://www.newtonsoft.com/json 中

这是一个非常简单的示例,可以从您的数据模型中生成一个简单的 JSON 字符串:

public partial class TreeView : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public string GetTreeViewJson()
    {
        return JsonConvert.SerializeObject(GetTreeView());
    }

    public IEnumerable<CategoryRootTreeModel> GetTreeView()
    {
        List<CategoryRootTreeModel> items = new List<CategoryRootTreeModel>();
        using (var sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
        {
            var sqlCommand = new SqlCommand("SELECT * FROM [dbo].[Category_Tbl]", sqlConnection);
            sqlCommand.CommandType = System.Data.CommandType.Text;

            sqlConnection.Open();

            using (var reader = sqlCommand.ExecuteReader())
            {
                while (reader.Read())
                {
                    items.Add(new CategoryRootTreeModel
                    {
                        catid = (int)reader["ID"],
                        expanded = true,
                        text = reader["Categories"].ToString()
                    });
                }
            }
        }
        items.ForEach(item => bindSubCategeories(item));
        return items;
    }

    void bindSubCategeories(CategoryRootTreeModel model)
    {
        using (var sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
        {
            var sqlCommand = new SqlCommand("SELECT * FROM [dbo].[SubCategory_Tbl] WHERE CATID = @p0", sqlConnection);
            sqlCommand.CommandType = System.Data.CommandType.Text;
            sqlCommand.Parameters.AddWithValue("@p0", model.catid);

            sqlConnection.Open();

            using (var reader = sqlCommand.ExecuteReader())
            {
                while (reader.Read())
                {
                    model.items.Add(new CategoryTreeItemModel
                    {
                        catid = (int)reader["ID"],
                        subcatid = (int)reader["CATID"],
                        text = reader["Subcategories"].ToString()
                    });
                }
            }
        }
    }



}

public class CategoryRootTreeModel
{
    public CategoryRootTreeModel()
    {
        this.items = new List<CategoryTreeItemModel>();
    }

    public string text { get; set; }

    public bool expanded { get; set; }

    public int catid { get; set; }

    public List<CategoryTreeItemModel> items { get; set; }
}

public class CategoryTreeItemModel
{
    public string text { get; set; }

    public int catid { get; set; }

    public int subcatid { get; set; }
}

然后可以在您的 aspx 文件中调用,例如

&lt;%= GetTreeViewJson() %&gt;

这将输出一个很长的字符串,例如...

[{"text":"Projects","expanded":true,"catid":1,"items":[{"text":"Residential Projects","catid":1,"subcatid":1},{"text":"Commercial Projects","catid":2,"subcatid":1},{"text":"Residential Apartment","catid":3,"subcatid":2},{"text":"Independent/Builder Floor","catid":4,"subcatid":2},{"text":"Independent House/Villa","catid":5,"subcatid":2},{"text":"Residential Land","catid":6,"subcatid":2},{"text":"Studio Apartment","catid":7,"subcatid":2},{"text":"Farm House","catid":8,"subcatid":2},{"text":"Service Apartments","catid":9,"subcatid":2},{"text":"Commercial Shops","catid":10,"subcatid":3},{"text":"Commercial Showrooms","catid":11,"subcatid":3},{"text":"Commercial Office/Space","catid":12,"subcatid":3},{"text":"Commercial Land/Inst. Land","catid":13,"subcatid":3}]},{"text":"Residential","expanded":true,"catid":2,"items":[{"text":"Residential Projects","catid":1,"subcatid":1},{"text":"Commercial Projects","catid":2,"subcatid":1},{"text":"Residential Apartment","catid":3,"subcatid":2},.....]

现在我们将序列化的数据添加到我们的视图中,我们可以轻松地将其添加到 kendo 数据源中,例如...

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    <link rel="stylesheet" type="text/css" href="http://cdn.kendostatic.com/2014.3.1119/styles/kendo.common.min.css" />
    <link rel="stylesheet" type="text/css" href="http://cdn.kendostatic.com/2014.3.1119/styles/kendo.default.min.css" />
    <script type="text/javascript" src="http://cdn.kendostatic.com/2014.3.1119/js/kendo.all.min.js"></script>

    <div id="list1"></div>

    <script type="text/javascript">

        $(function () {
            $('#list1').kendoTreeView({
                checkboxes: {
                    checkChildren: true
                },
                dataSource:<%= GetTreeViewJson() %>
            });
        });
    </script>
</asp:Content>

现在,这样做有点笨拙,因为我宁愿通过 ajax 返回一个不错的 JSON 响应,但最终得到一个非常简单的列表,如 JS 小提琴所示。

更多信息:

要从 TreeView 获取检查值,您可以遵循 Telerik 提供的 API 指南,尤其是检查事件。

http://docs.telerik.com/kendo-ui/api/javascript/ui/treeview#events-check

这是一个示例: http://demos.telerik.com/kendo-ui/treeview/checkboxes

在示例中,他们响应check 事件并使用函数checkedNodeIds(nodes, checkedNodes) 创建一个javascript 数组,这是他们作为示例提供的函数。您可以对其进行调整以更改页面上的文本框的值,例如。

<asp:TextBox runat="server" ID="CheckedFields" Text="" /><asp:Button runat="server" ID="SaveFields" Text="Save Fields" OnClick="SaveFields_Click" />

<div id="list1"></div>

<script type="text/javascript">

    function checkedNodeIds(nodes, checkedNodes) {
        for (var i = 0; i < nodes.length; i++) {
            if (nodes[i].checked) {
                checkedNodes.push(nodes[i].catid);
            }

            if (nodes[i].hasChildren) {
                checkedNodeIds(nodes[i].children.view(), checkedNodes);
            }
        }
    }

    // show checked node IDs on datasource change
    function onCheck() {
        var checkedNodes = [],
            treeView = $("#list1").data("kendoTreeView")
        checkedNodeIds(treeView.dataSource.view(), checkedNodes);
        $('#<%= CheckedFields.ClientID %>').val(checkedNodes.join(', '));
    }

    $(function () {
        $('#list1').kendoTreeView({
            checkboxes: {
                checkChildren: true
            },
            check: onCheck,
            dataSource:<%= GetTreeViewJson() %>
        });
    });
</script>

这将触发使用 'checkedNodes.join(',')' 方法将 id 更改为逗号分隔的数组。现在您会发现您可能需要找到更多信息,但是数组nodes[] 中的每个node 都包含您从可用代码中传入的所有字段(加上一些额外内容),您可以通过以下方式获得非常有创意跟踪您选中的选项。

干杯

【讨论】:

  • 那是极好的@Nico,但我想绑定来自SQL 的数据并且对webservices 了解不多:(
  • 在 `dataSource: });` jquery code @Nico 上出现语法错误
  • 您是否尝试过运行示例? Visual Studio intellisense 不喜欢该示例,因为它对 Visual Studio 来说是无效的 javascript :)
  • 现在出现错误`内容控件必须是内容页中的顶级控件或引用母版页的嵌套母版页。`
  • 从示例中删除 &lt;asp:Content /&gt; 标签,因为这些标签应该已经存在于您的网页中。
【解决方案2】:
ddlCategory.DataSource = CategoryDataAcces.GetAllMain();
ddlCategory.DataBind();

private void ddlCategory_SelectedIndexChanged(object sender, EventArgs e) 
{
    if (ddlCategory.SelectedIndex < 0) 
        return;

    int categoryID = int.Parse(ddlCategoryID.SelectedValue.ToString());
    ddlSubCategory.DataSource = CategoryDataAccess.GetByCategoryID(categoryID);
    ddlSubCategiry.DataBind();
}

无法访问编程环境,但我认为这应该可以帮助您入门。

【讨论】:

  • return后面需要分号
  • 谢谢。还在习惯平板电脑。
【解决方案3】:

将您的第一个表的数据源(即“类别”)绑定到下拉列表。

然后在下拉列表 OnSelectedItem 事件中获取所选类别的 id。并将其传递给查询找到的子类别。然后再次绑定到下拉列表

看看这个。 http://www.dotnetfox.com/articles/dropdowncheckboxes-or-drop-down-checkboxlist-control-in-Asp-Net-1100.aspx

http://www.aspdotnet-suresh.com/2014/03/jquery-multiselect-dropdown-list-with-checkboxes.html

【讨论】:

  • 你能举个小例子吗?
  • 您可以在上述链接中找到示例。希望对您有所帮助。
  • 我已经访问过这个网站,但这仅适用于类别。我想同时绑定类别和子类别
【解决方案4】:

使用引导多选插件。您可以在此示例中找到更多信息:

http://davidstutz.github.io/bootstrap-multiselect/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多