循环通过动态生成的textareas

时间:2013-05-20 19:15:48

标签: .net vb.net

我正在尝试遍历并在我的vb.net网页上检索一堆动态生成的textareas的值。

用户可以通过jQuery添加textareas,当他们点击保存按钮时,我需要收集他们输入这些textareas的所有数据。

所以我写了一个小循环(下面),但即使填写了所有文本区域,它也总是抛出一个空错误。

感谢您的任何帮助或建议!

这是我的代码:

    Dim divContainter As HtmlGenericControl = CType(Page.FindControl("divContainter"), HtmlGenericControl)

    For Each control As TextBox In divContainter.Controls.Cast(Of TextBox)()
        If TypeOf control Is TextBox Then
            'do stuff
            Response.Write(control.Text)
        End If

    Next

1 个答案:

答案 0 :(得分:2)

您将无法从服务器端检索jQuery生成的文本框。对于服务器控件,如果它们是在客户端创建的,则不存在。你可以做的是使用JSON捕获文本框并回发页面。

以下是我在类似情况下使用的示例代码:

    function SubmitResources() {
        var activeDiscipline = $('#<%=tcDisciplines.ClientID%> .ajax__tab_active').first().attr('id').replace(/\D/g, "");
        var ctrID = $('#<%=hfCTRID.ClientID%>').val();
        var ctrDescription = CKEDITOR.instances['<%=tbEditDescription.ClientID%>'].getData().replace(/[|]/g, "");

//before this part I retrieved the data from needed controls

        var json = activeDiscipline + "|" + ctrID + "|" + ctrDescription + "|"; // here I add initial data into the JSON variable

        $('#<%=tblEdit.ClientID%> .trRes').each(function () {
            var resID = $(this).find("#resource").attr("name");
            var resH = $(this).find(".resH").val();
            var resC = $(this).find(".resC").val();
            json += resID + ';' + resH + ';' + resC + '|'
        }); //this loop goes through generated text boxes and appends the data with separators

        var options = { //set JSON options
            type: "POST",
            url: window.location + "&Update=Resource", //append QueryString
            data: json,
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            async: false
        };

        $.ajax(options); //Postback
    }

将功能设置为按钮:

<asp:Button ID="btnEditSubmit" runat="server" Text="Submit" ValidationGroup="Edit" OnClientClick="SubmitResources()" />

转到.aspx.vb并处理Init事件

            If Not IsNothing(Request.QueryString("Update")) Then
                'If the query string was passed from jQuery, capture the JSON value and submit
                Dim sr As New StreamReader(Request.InputStream)
                Dim line As String = sr.ReadToEnd()
                Dim resources As String() = line.Substring(0, line.Length - 1).Split("|")

                'Do your magic here. Now 'line' looks like this: 0;10;100|1;20;200|2;200;2000. 'resources' is an array with values as so: 0;10;100 Loop through the array and get the needed data.
            End If