获取动态添加的输入字段的内容

Get content of dynamically added input fields

本文关键字:字段 输入 添加 获取 动态      更新时间:2023-09-26

单击按钮时,我正在使用JavaScript向网页添加额外的输入字段,并试图在ASP.NET中获取新输入字段的内容,但我只能访问原始输入字段,而不能访问使用JavaScript创建的新输入字段。

添加到的原始列表:

<ul class="add-event-list" id="eventList" runat="server">
    <li id="eventItemsList">
         <asp:TextBox name="event-info" TextMode="MultiLine" Columns="50" Rows="5" id="eventInfo" placeholder="Enter an Event..." runat="server"/>
         <label for="event-date" class="field-heading">Date</label>
         <asp:TextBox Type="date" name="event-date" id="eventDate" placeholder="Enter a Date..." runat="server"/>
     </li>
</ul>
<button class="btn add-event-btn" onclick="return false" >Add Event <span class="glyphicon glyphicon-plus"/></button>

点击按钮:

$('.add-event-btn').on('click', function () {
    var list = $('#eventItemsList').clone();
    $('.add-event-list').append(list);
});

点击提交:

<button class="grey-btn" id="buttonSubmitHouse" onserverclick="buttonSubmitHouse_ServerClick" runat="server">Submit</button>

仅显示ul中的原始元素:

protected void buttonSubmitHouse_ServerClick(object sender, EventArgs e)
{
    foreach (Control item in eventList.Controls)
    {
        Control Test = item;
    }
}

遇到这个问题的原因是,它们实际上并没有在服务器上呈现动态控件。这就是为什么你不能遍历它们,服务器不知道它们的存在。最简单的方法是实现Web服务。

当您调用该服务时,您只需附加一个QueryString,然后执行所需的功能。所以从客户那里你会做:

$.ajax({
     type: '...',
     url: '...',
     dataType: 'json',
     success: (function (response) {
          // Do something with service response.
     })
});

根据您的技术,您可能会命中Controller或使用Generic Asp处理程序文件,因此您将锚定到传递给处理程序的HttpContext上。