下拉类别和子类别

时间:2015-05-05 05:22:54

标签: c# jquery sql asp.net

我在SQL中有两个表。

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

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

这样的东西

enter image description here

我搜索了谷歌,但没有任何有价值的结果。

4 个答案:

答案 0 :(得分:3)

不要插入另一家公司,但我(在很多情况下)使用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文件中调用它,例如

<%= GetTreeViewJson() %>

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

[{"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},.....]

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

<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更改为逗号分隔数组。现在您会发现您可能需要查找更多信息,但是数组node中的每个nodes[]都包含您从可用的代码中传入的所有字段(加上一些额外内容),您可以获得更多信息创意与您如何跟踪您选中的选项。

干杯

答案 1 :(得分:1)

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();
}

无法访问编程环境,除了我认为这应该有助于您入门。

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

将您的第一个表格的数据源绑定到“下载列表”。

然后在下拉列表中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