You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CS文件中控制动态HTML表格行值并批量提交至数据库?

问题

目前能处理固定行的数据提交,但动态生成额外输入行后,无法获取新增行对应ID的值并提交至数据库。希望将每行各ID对应的值存入属性,通过一个方法批量提交到数据库。

现有代码

HTML 代码

<tbody id="hiddenRows">
    <tr style="display:none;">
        <td><input id="ck" runat="server" type="checkbox"></td>
        <td>
            <asp:DropDownList runat="server" ID="ddlProductName" AutoPostBack="True"
                OnSelectedIndexChanged="ddlProductName_SelectedIndexChanged"></asp:DropDownList>
        </td>
        <td>
            <asp:Label ID="ddlSupliersName" runat="server" Text=""></asp:Label>
        </td>
        <td><input id="unitPrice" type="text" name="unitPirce" runat="server" /></td>
        <td><input id="quantity" type="text" name="quantity" runat="server" /></td>
        <td><input id="discount" type="text" name="discount" runat="server" /></td>
        <td><span id="subtotal"></span></td>
    </tr>
</tbody>

C# 后台代码

protected void Button3_Click(object sender, EventArgs e)
{
    using(OrderBiz biz = new OrderBiz())
    {
        DataSet ds = biz.SetOrderItem(ddlCompanName.SelectedValue, ddlContactName.SelectedValue
            , ddlProductName.SelectedValue, ddlSupliersName.Text, Convert.ToDecimal(unitPrice.Value)
            , Convert.ToInt32(quantity.Value), Convert.ToInt32(discount.Value) / 100 );
    }
}
解决方案

1. 定义订单项实体类

先创建实体类封装每行的订单数据:

public class OrderItem
{
    public string CompanyName { get; set; }
    public string ContactName { get; set; }
    public string ProductName { get; set; }
    public string SupplierName { get; set; }
    public decimal UnitPrice { get; set; }
    public int Quantity { get; set; }
    public decimal Discount { get; set; }
}

2. 修改前端动态生成规则

动态新增行时,将表单元素的name设为数组格式(比如productNames[]),放弃动态元素的runat="server",靠name识别数据。示例动态行结构:

<tr>
    <td><input type="checkbox" name="selectedRows" value="rowIndex" /></td>
    <td>
        <select name="productNames[]">
            <!-- 产品选项 -->
        </select>
    </td>
    <td><input type="hidden" name="supplierNames[]" value="" /><span class="supplierName"></span></td>
    <td><input type="text" name="unitPrices[]" /></td>
    <td><input type="text" name="quantities[]" /></td>
    <td><input type="text" name="discounts[]" /></td>
    <td><span class="subtotal"></span></td>
</tr>

注:供应商名称通过前端JS填充后,存入hidden字段提交,确保后端能获取到对应值。

3. 后端批量获取表单数据

在按钮点击事件中,通过Request.Form读取数组数据,组装成OrderItem列表:

protected void Button3_Click(object sender, EventArgs e)
{
    List<OrderItem> orderItems = new List<OrderItem>();
    string[] productNames = Request.Form.GetValues("productNames[]");
    string[] supplierNames = Request.Form.GetValues("supplierNames[]");
    string[] unitPrices = Request.Form.GetValues("unitPrices[]");
    string[] quantities = Request.Form.GetValues("quantities[]");
    string[] discounts = Request.Form.GetValues("discounts[]");
    string[] selectedRows = Request.Form.GetValues("selectedRows");

    if (productNames != null && productNames.Length > 0)
    {
        for (int i = 0; i < productNames.Length; i++)
        {
            // 跳过未勾选的行(如果需要只提交勾选行)
            if (selectedRows != null && !selectedRows.Contains(i.ToString()))
                continue;

            OrderItem item = new OrderItem();
            item.CompanyName = ddlCompanName.SelectedValue;
            item.ContactName = ddlContactName.SelectedValue;
            item.ProductName = productNames[i];
            item.SupplierName = supplierNames?[i] ?? string.Empty;
            item.UnitPrice = decimal.TryParse(unitPrices[i], out decimal price) ? price : 0;
            item.Quantity = int.TryParse(quantities[i], out int qty) ? qty : 0;
            item.Discount = int.TryParse(discounts[i], out int disc) ? disc / 100m : 0;

            orderItems.Add(item);
        }
    }

    // 调用批量提交方法
    using(OrderBiz biz = new OrderBiz())
    {
        DataSet ds = biz.BatchInsertOrderItems(orderItems);
    }
}

4. 修改Biz层支持批量提交

在OrderBiz中新增批量插入逻辑,推荐用参数化SQL避免注入:

public DataSet BatchInsertOrderItems(List<OrderItem> orderItems)
{
    string connStr = ConfigurationManager.ConnectionStrings["YourConnStr"].ConnectionString;
    using(SqlConnection conn = new SqlConnection(connStr))
    {
        conn.Open();
        string sql = @"INSERT INTO OrderItems 
                       (CompanyName, ContactName, ProductName, SupplierName, UnitPrice, Quantity, Discount)
                       VALUES (@CompanyName, @ContactName, @ProductName, @SupplierName, @UnitPrice, @Quantity, @Discount)";
        
        foreach(var item in orderItems)
        {
            using(SqlCommand cmd = new SqlCommand(sql, conn))
            {
                cmd.Parameters.AddWithValue("@CompanyName", item.CompanyName);
                cmd.Parameters.AddWithValue("@ContactName", item.ContactName);
                cmd.Parameters.AddWithValue("@ProductName", item.ProductName);
                cmd.Parameters.AddWithValue("@SupplierName", item.SupplierName);
                cmd.Parameters.AddWithValue("@UnitPrice", item.UnitPrice);
                cmd.Parameters.AddWithValue("@Quantity", item.Quantity);
                cmd.Parameters.AddWithValue("@Discount", item.Discount);
                cmd.ExecuteNonQuery();
            }
        }
    }
    return new DataSet();
}

内容的提问来源于stack exchange,提问作者hhw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 18:57:53