You need to enable JavaScript to run this app. C# MVC 无需回传控制器实现输入变更时实时计算总额
优惠活动
大模型
产品
解决方案
定价
更多

C# MVC 无需回传控制器实现输入变更时实时计算总额

实时联动计算总额的代码修改方案

核心修改点

  • 调整输入触发事件:将Amount1、Amount2输入框原本的onblur = "recalc()"失焦触发,替换为oninput = "recalc()"输入即时触发,无需等用户切换焦点就可以同步更新总额
  • 修正JS计算逻辑:原代码直接操作服务端模型对象m的写法无法生效,前端JS无法直接访问服务器端的C#模型实例,需通过DOM接口读取输入框值、写回计算结果
  • 增加数值容错:对空输入、非数字内容做兼容处理,默认按0计算结果,同时保留两位小数适配美元金额的显示规范
  • 兼容后端提交逻辑:计算结果直接写入总额输入框的原生value属性,表单回传控制器时,模型可以正常绑定接收到TotalAmount的计算值,无需额外处理

无需修改的部分

原有Model代码完全符合需求,不需要做调整,保留如下代码即可:

using System;

namespace SandboxJScalc.Models
{
    public class CommonInfo
    {
        public decimal Amount1 { get; set; }
        public decimal Amount2 { get; set; }
        public decimal TotalAmount { get; set; }
    }
}

修改后的完整View代码

@model SandboxJScalc.Models.CommonInfo
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <link href="~/css/site.css" rel="stylesheet" />
    <meta name="viewport" content="width=device-width" />
    <title>Sandbox JS Calc</title>
</head>

<body>
    <h1 style="text-align: center">Sandbox JS Calc</h1>
    <br />
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <table align="center">
            <tr>
                <td>Amount 1 :</td>
                <td>
                    @Html.TextBoxFor(m => m.Amount1,
                         new { @class = "{number: true}  small-input", oninput = "recalc()" })
                </td>
            </tr>
            <tr>
                <td>Amount 2 :</td>
                <td>
                    @Html.TextBoxFor(m => m.Amount2,
                         new { @class = "{number: true}  small-input", oninput = "recalc()" })
                </td>
            </tr>
            <tr>
                <td>Total Amount :</td>
                <td>@Html.TextBoxFor(m => m.TotalAmount, new { @readonly = "readonly" })</td>
            </tr>
        </table>
    }
</body>
</html>

<script language="javascript">
    function recalc() {
        // 读取两个输入框的值,空值/非数字默认按0计算
        const amount1 = parseFloat(document.getElementById("Amount1").value) || 0;
        const amount2 = parseFloat(document.getElementById("Amount2").value) || 0;
        // 计算总额并保留2位小数
        const total = amount1 + amount2;
        // 将计算结果写入总额输入框
        document.getElementById("TotalAmount").value = total.toFixed(2);
    }
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.25 08:36:04