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

模态框局部视图表单内jQuery DataTable添加行获取输入值失败

Hey there! Let's break down your problems step by step— I’ve run into similar modal/DataTable quirks in ASP.NET Core before, so I think I can help you out.


1. Fixing the Empty Input Value Issue

First up, the core problem: why are prodId and prodQty coming up empty when you click the button? The most likely culprit is dynamic DOM loading. If your modal is loaded as a partial view via AJAX (which it sounds like, since it's triggered by a button), the #AddProdBtn element doesn't exist when your initial $(document).ready() runs. That means the click event you bound never attaches to the button.

Solution: Use Event Delegation

Instead of binding directly to the button, attach the event to a parent element that exists when the page first loads (like document or the modal container). This way, the event will "delegate" to the button even when it's added later.

Update your JavaScript code to this:

$(document).on('click', '#AddProdBtn', function () {
    const prodId = $('#prodId').val().trim();
    const prodQty = $('#prodQty').val().trim();
    
    // Add quick validation to avoid empty rows
    if (prodId && prodQty) {
        $('#returnLinesGrid').dataTable().fnAddData([prodId, prodQty]);
        // Optional: Clear inputs after adding the row
        $('#prodId').val('');
        $('#prodQty').val('');
    } else {
        alert('Please fill in both Product ID and Quantity!'); // Swap this with your app's alert component if needed
    }
});

Quick HTML Fix (Layout Cleanup)

I also noticed your input fields aren't wrapped in a .row container, which might cause layout issues (though not the empty value problem). Wrap them to keep your Bootstrap grid consistent:

<div class="modal-body row">
    <div class="md-form col-3 create-only">
        <input type="number" value="" id="prodId" placeholder="@LabelResource.SelectProdId" />
    </div>
    <div class="md-form col-3 create-only">
        <input type="text" value="" id="prodQty" placeholder="@LabelResource.SelectProdQuantity" />
    </div>
    <div class="col-6 d-flex align-items-center">
        <button type="button" id="AddProdBtn">@ButtonResource.AddProduct</button>
    </div>
</div>

2. Serializing Table Data to asp-for Fields & Form Nesting

Is serializing table data to asp-for fields feasible?

Absolutely! You just need to map your DataTable rows to your model's ReturnLines collection properly using ASP.NET Core's model binding rules. Here's how to do it:

Step 1: Add Hidden Fields for Model Binding

Every time you add a row to the DataTable, insert hidden fields into your main form that match the structure of your ReturnLine model. ASP.NET Core will automatically bind these to your ReturnLines collection when you submit the form.

Update your button click handler to include this:

$(document).on('click', '#AddProdBtn', function () {
    const prodId = $('#prodId').val().trim();
    const prodQty = $('#prodQty').val().trim();
    
    if (prodId && prodQty) {
        // Add row to DataTable
        $('#returnLinesGrid').dataTable().fnAddData([prodId, prodQty]);
        
        // Get current number of rows to generate the correct index for model binding
        const lineCount = $('#returnLinesGrid tbody tr').length;
        
        // Append hidden fields to the main form
        const mainForm = $('form[asp-action="Create"]');
        mainForm.append(`<input type="hidden" name="ReturnLines[${lineCount-1}].ProductId" value="${prodId}" />`);
        mainForm.append(`<input type="hidden" name="ReturnLines[${lineCount-1}].Quantity" value="${prodQty}" />`);
        
        // Clear inputs
        $('#prodId').val('');
        $('#prodQty').val('');
    } else {
        alert('Please fill in both Product ID and Quantity!');
    }
});

Just make sure your ReturnLine model has ProductId and Quantity properties that match the hidden field names.

Form Nesting Concern

You’re 100% right about HTML5 not allowing nested forms— but you don’t need an extra form here! Your prodId and prodQty inputs are already inside the main form, so you can access their values directly without wrapping them in another form. The approach above uses the existing form to hold the hidden fields for model binding, which works perfectly.


Extra Tips

  • If you add a way to delete rows from the DataTable, remember to delete the corresponding hidden fields too— otherwise you’ll send invalid data to the server.
  • For better user experience, add client-side validation (e.g., check that prodId is a number and prodQty is a positive value) before adding the row.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:30:49