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

ASP.NET Core MVC表单提交时Model属性无法赋值问题求助

问题分析与解决方案

核心问题

你的Razor视图未声明绑定的模型类型,导致asp-for标签助手无法生成正确的表单字段name属性,ASP.NET Core的模型绑定系统无法将表单提交的值映射到FutureValueModel的属性上,最终所有属性保留默认值0。

解决方案

在视图的代码块下方添加@model指令,明确指定模型的完整命名空间:

@{
    Layout = null;  //not a razor layout
}
@model FutureValue.Models.FutureValueModel

添加后,asp-for会自动生成与模型属性名称匹配的name属性(例如name="MonthlyInvestment"),表单提交时,模型绑定就能正确将用户输入的值赋值到对应属性中。

额外检查点

  1. 数据格式验证:确保输入的数值格式符合服务器区域设置(例如decimal类型输入使用.作为小数分隔符,避免使用,;若需兼容多格式,可在模型属性上添加[DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]属性)
  2. 确认表单提交数据:打开浏览器开发者工具的Network标签,查看POST请求的Form Data,确认字段名和输入值是否正确发送到服务器
  3. 模型属性权限:你的模型属性已设置为public get; set;,符合模型绑定要求,无需修改

修改后的完整视图代码

@{
    Layout = null;  //not a razor layout
}
@model FutureValue.Models.FutureValueModel

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Home Page</title>
    </head>

    <body>
        <h1>Future Value Calculator</h1>
        <form asp-action="Index" method="post">
            <div>
                <label asp-for="MonthlyInvestment">Monthly Investment:</label>
                <input asp-for="MonthlyInvestment" />
            </div>
            <div>
                <label asp-for="YearlyInterestRate">Yearly Interest Rate:</label>
                <input asp-for="YearlyInterestRate" />
            </div>
            <div>
                <label asp-for="Years">Number of Years:</label>
                <input asp-for="Years" />
            </div>
            <div>
                <label>Future Value:</label>
                <input value="@ViewBag.FV.ToString("C2")" readonly />
            </div>
            <button type="submit">Calculate</button>
            <a asp-action="Index">Clear</a>
        </form>
    </body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.11 20:33:15