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

ASP.NET中DeliveryCharge字段提交问题:display:none与visibility:hidden困境

解决方案

核心误区纠正

首先明确:readonly属性的输入框会随表单正常提交,只有disabled属性的元素才会被排除在表单提交之外。你之前额外添加隐藏字段是没必要的,直接用readonly的输入框就能同时满足「灰色不可编辑」和「表单提交」的需求。

修正后的最简代码

<div>
    <label asp-for="DeliveryCharge" class="w-100">DeliveryCharge:</label>
    <div style="display:flex;">
        <!-- 仅用readonly输入框,既做展示又支持提交 -->
        <input readonly asp-for="DeliveryCharge" type="number" step="0.01" 
               style="flex-grow: 1; background-color: #e9ecef; border-color: #ced4da;" 
               id="deliveryChargeInput" />
        <button type="button" onclick="calculateDeliveryCharge()">compute</button>
    </div>
    <span asp-validation-for="DeliveryCharge" class="text-danger" id="deliveryChargeDanger"></span>
</div>
function calculateDeliveryCharge() {
    // 替换成你的实际计算逻辑
    const calculatedCharge = 12.50; 
    // 更新输入框值,该值会随表单自动提交
    document.getElementById('deliveryChargeInput').value = calculatedCharge;
}

特殊场景下的隐藏字段方案

如果因业务需求必须使用隐藏字段,解决decimal绑定问题的关键是不要给隐藏字段设置字符串类型默认值(比如你之前写的value="USD"),让JavaScript设置数值即可,ASP.NET会自动解析为decimal类型:

<div>
    <label asp-for="DeliveryCharge" class="w-100">DeliveryCharge:</label>
    <div style="display:flex;">
        <input readonly asp-for="DeliveryCharge" type="number" step="0.01" 
               style="flex-grow: 1; background-color: #e9ecef; border-color: #ced4da;" 
               id="deliveryChargeInput" />
        <!-- 隐藏字段用于提交,asp-for自动处理类型绑定 -->
        <input asp-for="DeliveryCharge" type="hidden" id="deliveryChargeHidden" />
        <button type="button" onclick="calculateDeliveryCharge()">compute</button>
    </div>
    <span asp-validation-for="DeliveryCharge" class="text-danger" id="deliveryChargeDanger"></span>
</div>
function calculateDeliveryCharge() {
    const calculatedCharge = 12.50;
    // 同时更新展示框和隐藏字段
    document.getElementById('deliveryChargeInput').value = calculatedCharge;
    document.getElementById('deliveryChargeHidden').value = calculatedCharge;
}

补充说明

  • readonly输入框的灰色样式通过background-color: #e9ecef; border-color: #ced4da;实现,和Bootstrap默认readonly样式一致
  • display:none的表单元素不会阻止提交,只要带有正确的name属性(asp-for会自动生成),你之前遇到的提交问题大概率是其他原因导致的

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 04:01:08