如何访问我通过jQuery添加的asp.net代码中的列表框项

时间:2016-06-18 18:48:02

标签: c# jquery asp.net webforms listbox

我正在开发一个项目,目前我正在做一个属于发布文章页面的模块。在此页面中,我们可以选择使用文本框和按钮添加关键字。

我是通过使用jQuery将textbox输入关键字成功添加到列表框来完成的。

如果用户想要在添加到列表框后删除任何特定关键字,则用户可以通过在列表框中选择该关键字将其删除,然后会出现删除按钮。如果用户单击从列表框中删除的删除按钮关键字。

问题

使用jQuery成功将关键字添加到列表框但我无法访问C#代码后面的列表框项

Asp.net页面列表框:

<a id="arkyw" href="#/"><font color="#cc0000">Remove Keyword</font></a>
<span id="spKeyword" style="color:#e74c3c;"></span>    
<asp:ListBox ID="listBoxKeywords" runat="server" CssClass="list-group" style="border:0px; overflow-y:hidden; height:83px; width:300px;">

jQuery的:

var count = [];
    var i = 0;
    $("#btnAddKeyword").click(function () {        
        var txt = $("#txtkeyword").val();
        $('[id$=listBoxKeywords]').show();
        if (jQuery.inArray(txt, count) != "-1") {
            $("#spKeyword").text('Keyword alread exists');
        } else {
            var listCount = $('[id$=listBoxKeywords] option').length;
            if (listCount <= 4) {
                count[listCount] = txt;
                var alreadyExist = false;
                $('[id$=listBoxKeywords] option').each(function () {
                    if ($(this).val() == txt) {
                        $("#spKeyword").text('Keyword alread exists');
                        alreadyExist = true;
                        return;
                    }
                });
                if (!alreadyExist) {
                    $('[id$=listBoxKeywords]').append($('<option></option>').attr('value', count[listCount]).text(txt));
                }
            } else {
                $("#spKeyword").text('5 Keyword limit exceed');
            }
        }
    });
    //Remove Value from the List
    $('[id$=listBoxKeywords]').click(function (e) {        
        var $target = $(e.target);
        if ($target.is('option')) {
            $("#arkyw").show();            
        }
    });
    $("#arkyw").click(function () {
        var a = $('[id$=listBoxKeywords] option:selected').val();
        var id = $('[id$=listBoxKeywords] option').length;
        //alert('ListCount : ' + a);
        //alert('Total List Item : ' + id);
        //alert('After Remove : ' + count[a-1]);
        count = jQuery.grep(count, function (e) {
            $('[id$=listBoxKeywords] option:selected').remove();
            return e != a;

        });        
    });

如何在C#代码后面访问列表框项?

1 个答案:

答案 0 :(得分:1)

您无法访问服务器端的客户端数据。

在回发时清除了客户端数据。

ListBox中的项目,在客户端和浏览器级别添加。

您可以使用Json或Hidden Field将客户端数据保存到数据库中。 类似主题:

https://www.experts-exchange.com/questions/28379748/Creating-rows-dynamically-on-client-side-and-saving-them-to-database-on-server-side.html

您可以将列表框项数据添加到字符串变量并将其保存到隐藏字段。 例如,您有3个项目:

第1项

第2项

第3项

当在客户端添加任何项目时,Create string看起来像这样:

,第1项,

所以最后你有这个字符串:

,第1项,第2项,第3项,

将其保存到隐藏字段并读取服务器端的隐藏字段并拆分字符串,然后将每个字符串保存到数据库并从服务器端代码中读取它。