JavaScript 添加了在 c# 中无法访问的行

JavaScript added rows not accessible in c#

我正在 asp.net 制作网页。我用 runat="server" 创建了一个 HTML table。我通过从输入框中获取值,使用 JavaScript 添加了一些行。我需要在 c# 后面的代码中访问这些行。当我在后面的代码中使用此 table 时,它只给我一行,我将其添加为 table 部分中的 HTML 标题。它不考虑 JavaScript 中添加的行。有什么方法可以访问这些行吗?

我的HTML代码:

<table id="tblStaff" border="1" runat="server">
    <tr>
        <th>S. No.</th>
        <th>Staff Name</th>
        <th>Room</th>
        <th>Phone No.</th>
        <th>Remove</th>
    </tr>
</table>

Javascript代码:

function addStaff()
{
    var tbl = document.getElementById('tblStaff');
    var lastRow = tbl.rows.length;
    // if there's no header row in the table, then iteration = lastRow + 1
    var iteration = lastRow;
    var row = tbl.insertRow(lastRow);           

    var cell0 = row.insertCell(0);
    var textNode = document.createTextNode(iteration);
    cell0.appendChild(textNode);

    var cell1 = row.insertCell(1);
    var textNode = document.createTextNode(document.getElementById('txtStaffName').value);
    cell1.appendChild(textNode);

    var cell2 = row.insertCell(2);
    textNode = document.createTextNode(document.getElementById('txtRoomNo').value);
    cell2.appendChild(textNode);

    var cell3 = row.insertCell(3);
    textNode = document.createTextNode(document.getElementById('txtPhoneNo').value);
    cell3.appendChild(textNode);

    var lastCell = row.insertCell(4);
    var el = document.createElement('input');
    el.type = 'button';
    el.name = 'btnDelete' + iteration;
    el.id = 'btnDelete' + iteration;
    el.value = 'Remove';
    el.size = 40;
    el.setAttribute('onclick', 'deleteRow(' + iteration + ');');
    lastCell.appendChild(el);         
}

看起来您的 addStaff() 函数只添加到前端的 table。如果我可以指出,C# 是在服务器端执行的,因此,您的 javascript 添加的行在您的 C# 查找它们时不存在。

就像 Florian Gl 所建议的那样,您可以在 addStaff() 函数中包含一个 ajax 提交,它还会发送 javascript 在浏览器 table 中显示的任何行,到后端的 C#。在 C# 中拥有数据后,您可以继续发送电子邮件,甚至可以选择保存数据库...

我建议让用户通过表单添加一些数据,然后将其发送到服务器并将其存储在您想要的位置。如果成功,将重新呈现的 table 添加到响应中并在客户端呈现它,或者只添加新的行客户端。在服务器端你不能访问新行,但是你可以访问它的数据模型,这应该足够了。

如果您需要进一步的建议,您应该详细说明为什么您想要访问服务器端的那些行。

编辑: 看看 this fiddle。在那里你可以看到你的 table 必须的结构。现在,如果您想添加一个用户,只需按此格式添加一个新行,其中 name 中的 index 用户递增。现在,如果您点击提交,所有用户都将作为一个数组发送到服务器,您可以在其中遍历它们并发送电子邮件。

您的网络 api 方法可能如下所示:

//route url/to/api
public void AddNewUser(User[] users) 
{
   //iterate through users and send email
}

试试这个

using System.Web.UI.HtmlControls;

 foreach (HtmlTableRow row in tblStaff.Rows)
          {
            string txtCell0 = row.Cells[0].InnerText; 
            string txtCell1 = row.Cells[1].InnerText; 
          }