2013-05-20 48 views
1

我试图循环浏览并在我的vb.net网页上检索一堆动态生成的textareas的值。循环浏览动态生成的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

我认为....控制生成在客户端,所以这些控件不会在服务器端在回发事件。你会得到这些值。但是,当页面回发时,则通过FORM字段通过页面接收值。 – Nps

+0

@Nps我不知道我跟着你... – SkyeBoniwell

+1

动态创建控制在客户端不会被发回服务器。但它只是发布可通过Request.Form [“”]访问的值。根据这些信息,您可以在回发事件中创建控件,以在响应返回客户端时显示控件和值。 – Nps

回答

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