正在代码隐藏中检索选定ListBox项的属性数据

Retrieving attribute data from selected ListBox items in code behind

本文关键字:ListBox 属性 数据 代码 隐藏 检索      更新时间:2023-09-26

我有一个使用asp.net和C#的web应用程序。我有一个ListBox,用户可以在其中选择多个项目。它们使用属性属性进行分组。我需要在按钮单击事件的代码后面包含此属性。我想我可以在客户端设置属性值,它们在服务器端也可以使用,但我已经了解到事实并非如此。

我不知道该怎么办。每个ListItem都有一个Name、Value和Group,我希望在服务器端有它们。名称和值已在服务器端可用。我需要与每个选定项目关联的组。我应该为每个选定项目创建一个隐藏字段吗?是否应该有一个隐藏字段,其中包含与每个分组相关联的分组和值?我有一个设置分组属性的jquery函数。我想用它来设置隐藏字段,但我不确定我是应该使用一个隐藏字段还是选择尽可能多的项目。

这是我已经拥有的javascript:

$(document).ready(function () {
//Create groups for recipient dropdown list
$(".chosen-select option[grouping='GlobalGroups']").wrapAll("<optgroup label='Global Groups'>");
$(".chosen-select option[grouping='PersonalGroups']").wrapAll("<optgroup label='Personal Groups'>");
$(".chosen-select option[grouping='Individuals']").wrapAll("<optgroup label='Individuals'>");
//Configure the ListBox using the 'chosen' jquery plugin
$(".chosen-select").chosen({
    search_contains: true,
    no_results_text: "Sorry, no match!",
    allow_single_deselect: true
});
$('.chosen-container').css('width', '600px');
//set attribute property for selected list
$(".chosen-select").chosen().change(function (evt) {
    $(".chosen-select").find("option:selected").each(function () {
        var label = $(this).closest('optgroup').prop('label');
        if (label == "Global Groups") {
            $(this).attr("grouping", "GlobalGroups");
        }
        else if (label == "Personal Groups") {
            $(this).attr("grouping", "PersonalGroups");
        }
        else {
            $(this).attr("grouping", "Individuals");
        }
    });
});

});

这是HTML:

<asp:ListBox ID="lstBoxTo" runat="server" SelectionMode="Multiple"
  data-placeholder="Choose recipient(s)…" multiple="true" class="chosen-select">
</asp:ListBox>

对于任何有此问题的。。。我使用了一个隐藏字段asp:HiddenField,并将所有选择添加到分号分隔的字符串中。我解析了代码后面的字符串,以确定收件人是组还是个人。这是我的最后一个jquery脚本:

 $(".chosen-select").chosen().change(function (evt) {
            $("#hdnRecipientAttr").val("");
            $(".chosen-select").find("option:selected").each(function () {
                var label = $(this).closest('optgroup').prop('label');
                var currentHdnValue = $("#hdnRecipientAttr").val();
                if (label == "Individuals") {
                    var attrText = "Individuals-" + $(this).prop('value') + ";";
                    $("#hdnRecipientAttr").val(currentHdnValue + attrText);
                }
                else {
                    var attrText = "Group-" + $(this).prop('value') + ";";
                    $("#hdnRecipientAttr").val(currentHdnValue + attrText);
                }
            });
            //remove ending semicolon
            var hdnValue = $("#hdnRecipientAttr").val();
            $("#hdnRecipientAttr").val(hdnValue.slice(0, -1));
        });